You can subscribe to this list here.
2006 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(11) |
Dec
(20) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2007 |
Jan
|
Feb
|
Mar
|
Apr
(7) |
May
(24) |
Jun
(15) |
Jul
(5) |
Aug
(21) |
Sep
(85) |
Oct
(9) |
Nov
|
Dec
|
2008 |
Jan
(15) |
Feb
(11) |
Mar
|
Apr
(2) |
May
(3) |
Jun
|
Jul
|
Aug
|
Sep
(29) |
Oct
(47) |
Nov
(1) |
Dec
(1) |
2009 |
Jan
(8) |
Feb
(12) |
Mar
(14) |
Apr
(4) |
May
(1) |
Jun
|
Jul
(5) |
Aug
|
Sep
|
Oct
(11) |
Nov
(18) |
Dec
|
2010 |
Jan
|
Feb
|
Mar
(1) |
Apr
(3) |
May
(24) |
Jun
|
Jul
(1) |
Aug
(7) |
Sep
(5) |
Oct
(3) |
Nov
(4) |
Dec
|
2011 |
Jan
|
Feb
|
Mar
(13) |
Apr
(3) |
May
(2) |
Jun
|
Jul
(1) |
Aug
(24) |
Sep
(3) |
Oct
|
Nov
|
Dec
(29) |
2012 |
Jan
(5) |
Feb
(5) |
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
(3) |
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2013 |
Jan
|
Feb
|
Mar
|
Apr
(9) |
May
(1) |
Jun
|
Jul
|
Aug
(2) |
Sep
|
Oct
|
Nov
|
Dec
|
2015 |
Jan
|
Feb
|
Mar
|
Apr
(1) |
May
(1) |
Jun
|
Jul
(3) |
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
2017 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
(5) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <snt...@us...> - 2010-08-16 22:30:25
|
Revision: 166 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=166&view=rev Author: snthomas99 Date: 2010-08-16 22:30:16 +0000 (Mon, 16 Aug 2010) Log Message: ----------- Fixed log file output in linux and added directory location to bugs fail message Modified Paths: -------------- trunk/R2OpenBUGS/DESCRIPTION trunk/R2OpenBUGS/R/bugs.run.R trunk/R2OpenBUGS/R/bugs.script.R trunk/R2OpenBUGS/inst/NEWS Modified: trunk/R2OpenBUGS/DESCRIPTION =================================================================== --- trunk/R2OpenBUGS/DESCRIPTION 2010-08-10 02:53:35 UTC (rev 165) +++ trunk/R2OpenBUGS/DESCRIPTION 2010-08-16 22:30:16 UTC (rev 166) @@ -1,7 +1,7 @@ Package: R2OpenBUGS Title: Running OpenBUGS from R / S-PLUS Date: 2010-08-5 -Version: 1.0-0 +Version: 3.0-1 Author: originally written as R2WinBUGS by Andrew Gelman <ge...@st...>; changes and packaged by Sibylle Sturtz <st...@st...> and Uwe Ligges <li...@st...>. Modified: trunk/R2OpenBUGS/R/bugs.run.R =================================================================== --- trunk/R2OpenBUGS/R/bugs.run.R 2010-08-10 02:53:35 UTC (rev 165) +++ trunk/R2OpenBUGS/R/bugs.run.R 2010-08-16 22:30:16 UTC (rev 166) @@ -43,5 +43,6 @@ tmp <- scan("CODAchain1.txt", character(), sep="\n") } tmp<-tmp[1:min(100,length(tmp))] - if(length(grep("OpenBUGS did not run correctly", tmp)) > 0) stop("Look at the log file and\ntry again with 'debug=TRUE' to figure out what went wrong within OpenBUGS.") + if(length(grep("OpenBUGS did not run correctly", tmp)) > 0) stop(paste("Look at the log file in ",getwd(), + " and\ntry again with 'debug=TRUE' to figure out what went wrong within OpenBUGS.")) } Modified: trunk/R2OpenBUGS/R/bugs.script.R =================================================================== --- trunk/R2OpenBUGS/R/bugs.script.R 2010-08-10 02:53:35 UTC (rev 165) +++ trunk/R2OpenBUGS/R/bugs.script.R 2010-08-16 22:30:16 UTC (rev 166) @@ -49,7 +49,7 @@ thinUpdate <- paste("modelUpdate(", n.burnin, ",", n.thin, ")\n", sep="") cat( - "modelDisplay('log')\n", + if(.Platform$OS.type == "windows" | useWINE) "modelDisplay('log')\n", "modelCheck('", model, "')\n", "modelData('", data, "')\n", "modelCompile(", n.chains, ")\n", Modified: trunk/R2OpenBUGS/inst/NEWS =================================================================== --- trunk/R2OpenBUGS/inst/NEWS 2010-08-10 02:53:35 UTC (rev 165) +++ trunk/R2OpenBUGS/inst/NEWS 2010-08-16 22:30:16 UTC (rev 166) @@ -1,12 +1,11 @@ Changes to R2OpenBUGS: -===================== -First version 1.0.0 -- Converted R2WinBUGS to use OpenBUGS scripts. Eliminated BRugs calls. +====================== -Changes to R2WinBUGS: -===================== +Update 3.0-1 +- Converted R2WinBUGS to use OpenBUGS scripts and eliminated BRugs calls. -Update 2.1-17 + +Update 2.1-17 - fix as.bugs.array as reported by S. McKay Curtis Update 2.1-16 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <snt...@us...> - 2010-08-10 02:53:44
|
Revision: 165 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=165&view=rev Author: snthomas99 Date: 2010-08-10 02:53:35 +0000 (Tue, 10 Aug 2010) Log Message: ----------- Updated vignette and other doucmentation Modified Paths: -------------- trunk/R2OpenBUGS/R/bugs.script.R trunk/R2OpenBUGS/inst/NEWS trunk/R2OpenBUGS/inst/doc/bugs.tex trunk/R2OpenBUGS/man/as.bugs.array.Rd trunk/R2OpenBUGS/man/attach.all.Rd trunk/R2OpenBUGS/man/bugs.Rd trunk/R2OpenBUGS/man/bugs.data.Rd trunk/R2OpenBUGS/man/bugs.inits.Rd trunk/R2OpenBUGS/man/bugs.log.Rd trunk/R2OpenBUGS/man/bugs.script.Rd trunk/R2OpenBUGS/man/bugs.sims.Rd trunk/R2OpenBUGS/man/bugs.update.settings.Rd trunk/R2OpenBUGS/man/decode.parameter.name.Rd trunk/R2OpenBUGS/man/monitor.Rd trunk/R2OpenBUGS/man/read.bugs.Rd trunk/R2OpenBUGS/man/write.datafile.Rd trunk/R2OpenBUGS/man/write.model.Rd Added Paths: ----------- trunk/R2OpenBUGS/inst/doc/R2OpenBUGS.Rnw Removed Paths: ------------- trunk/R2OpenBUGS/inst/doc/R2WinBUGS.Rnw Modified: trunk/R2OpenBUGS/R/bugs.script.R =================================================================== --- trunk/R2OpenBUGS/R/bugs.script.R 2010-08-07 19:37:04 UTC (rev 164) +++ trunk/R2OpenBUGS/R/bugs.script.R 2010-08-10 02:53:35 UTC (rev 165) @@ -3,7 +3,7 @@ n.thin, model.file, debug=FALSE, is.inits, DIC=FALSE, useWINE=FALSE, newWINE=TRUE, WINEPATH=NULL, bugs.seed=NULL, summary.only=FALSE, - save.history=(.Platform$OS.type = "windows" | useWINE=TRUE), + save.history=(.Platform$OS.type == "windows" | useWINE==TRUE), bugs.data.file, bugs.inits.files, over.relax = FALSE) { Modified: trunk/R2OpenBUGS/inst/NEWS =================================================================== --- trunk/R2OpenBUGS/inst/NEWS 2010-08-07 19:37:04 UTC (rev 164) +++ trunk/R2OpenBUGS/inst/NEWS 2010-08-10 02:53:35 UTC (rev 165) @@ -1,3 +1,8 @@ +Changes to R2OpenBUGS: +===================== +First version 1.0.0 +- Converted R2WinBUGS to use OpenBUGS scripts. Eliminated BRugs calls. + Changes to R2WinBUGS: ===================== Copied: trunk/R2OpenBUGS/inst/doc/R2OpenBUGS.Rnw (from rev 161, trunk/R2OpenBUGS/inst/doc/R2WinBUGS.Rnw) =================================================================== --- trunk/R2OpenBUGS/inst/doc/R2OpenBUGS.Rnw (rev 0) +++ trunk/R2OpenBUGS/inst/doc/R2OpenBUGS.Rnw 2010-08-10 02:53:35 UTC (rev 165) @@ -0,0 +1,495 @@ +%\VignetteIndexEntry{R2OpenBUGS} +\documentclass{Z} +\usepackage{RdRW,thumbpdf} +\newcommand{\WinBUGS}{{\proglang{WinBUGS}}{}} +\newcommand{\OpenBUGS}{{\proglang{OpenBUGS}}{}} +\newcommand{\RW}{{\pkg{R2WinBUGS}}{}} +\newcommand{\RO}{{\pkg{R2OpenBUGS}}{}} +\renewcommand{\R}{{\proglang{R}}{}} +\setlength{\textheight}{23.5cm} + +\title{\RO{}:\protect\linebreak A Package for Running \OpenBUGS{} from \R{}} +\author{Sibylle Sturtz\thanks{\email{st...@st...}}\\Fachbereich Statistik\\Universit\"at Dortmund\\Germany + \And + Uwe Ligges\thanks{\email{li...@st...}}\\Fachbereich Statistik\\Universit\"at Dortmund\\Germany + \And + Andrew Gelman\thanks{\email{ge...@st...}}\\Department of Statistics\\Columbia University\\USA +} +\Plainauthor{Sibylle Sturtz, Uwe Ligges, Andrew Gelman} +\Plaintitle{R2OpenBUGS: A Package for Running OpenBUGS from R} + +\Abstract{ +The \RO{} package provides convenient functions to call \OpenBUGS{} from \R{}. It +automatically writes the data and scripts in a format readable by \OpenBUGS{} for processing in batch mode, which +is possible since version 1.4. After the \OpenBUGS{} process has finished, it is possible either to read the +resulting data into \R{} by the package itself---which gives a compact graphical summary of inference and +convergence diagnostics---or to use the facilities of the \pkg{coda} package for further analyses of the +output. Examples are given to demonstrate the usage of this package. +} + +\Keywords{\R{}, \OpenBUGS{}, interface, MCMC} +\Plainkeywords{R, OpenBUGS, interface, MCMC} + +\begin{document} +An earlier version of this vignette has been published by the Journal of Statistical Software:\\ +Sturtz S, Ligges U, Gelman A (2005): +``\RW{}: A Package for Running \WinBUGS{} from \R{}.'' +{\em Journal of Statistical Software}, 12(3), 1--16. +\RO{} was adapted from \RW{} by Neal Thomas. + + +\section{Introduction}\label{Introduction} +The usage of Markov chain Monte Carlo (MCMC) methods became very popular within the last decade. \OpenBUGS{} +\citep[\textbf{B}ayesian inference \textbf{U}sing \textbf{G}ibbs \textbf{S}ampling, ][] +{Spiegelhalter;Thomas;Best:2003} is a popular software for analyzing complex statistical models using MCMC +methods. This software uses Gibbs sampling \citep{Geman;Geman:1984,Gelfand;Smith:1990,Casella;George:1992} and the +Metropolis algorithm \citep{Metropolis;Rosenbluth;Rosenbluth;Teller;Teller:1953} +to generate a Markov chain by sampling from full conditional +distributions. +The \OpenBUGS{} software is available for free +at \url{http://www.OpenBUGS.info}. +An introduction to MCMC methods is given in \cite{Gilks;Richardson;Spiegelhalter:1996}. + +Using \OpenBUGS{}, the user must specify the model to run, and to load data and initial values for a specified +number of Markov chains. Then it is possible to run the Markov chain(s) and to save the results for the parameters +the user is interested in. Summary statistics of these data, convergence diagnostics, kernel estimates +etc.\ are available as well. +Nevertheless, some users of this software might be interested in saving the output and reading it into \R{} +\citep{RCore:2004} for further analyses. +\OpenBUGS{} comes with the ability to run the software in batch mode using scripts. + +The \RO{} package makes use of this feature and provides the tools to call \OpenBUGS{} +directly after data manipulation in \R{}. Furthermore, it is possible to +work with the results after importing them back into \R{} again, for example to create posterior predictive simulations or, more generally, graphical displays of data and posterior simulations \citep{gelman:2004}. +Embedding in R can also be useful for frequently changed data or processing a bunch of data sets, +because it is much more convenient to use some \R{} functions (possibly within a loop) +rather than using ``copy \& paste'' to update data in \OpenBUGS{} each time; however difficulties have been encountered in this area because both \R{} and \OpenBUGS{} can lock up RAM in the Windows operating system. + +\R{} is a ``language for data analysis and graphics'' and an open source and +freely available statistical software package implementing that language, see \url{http://www.R-project.org/}. +Historically, \R{} is an implementation of the award-winning \proglang{S} +language and system \citep{becker:1984r,becker:1988r,chambers:1992,chambers:1998}. +\R{} and \RO{} are available from \emph{CRAN} (Comprehensive \R{} Archive Network), +i.e., \url{http://CRAN.R-Project.org} or one of its mirrors. +\RO{} could be ported to the commercial \proglang{S} implementation +\textsc{S-Plus}. Minor adaptions would be needed since \textsc{S-Plus} +lacks some of \R{}'s functions and capabilities. +If an internet connection is available, \RO{} can be installed by typing +\verb+install.packages("R2OpenBUGS")+ at the \R{} command prompt. +Do not forget to load the package with \verb+library("R2OpenBUGS")+. + +The package \pkg{coda} by \cite{Plummer;Best;Cowles;Vines:2004} is very useful for the analysis of \OpenBUGS{}' +output, the reader might want to install this package as well. The CRAN package \pkg{boa} (Bayesian Output +Analysis Program) by \cite{Smith:2004} has similar aims. +\proglang{JAGS} (Just Another Gibbs Sampler) +by \cite{Plummer:2003} is a program for analysis of Bayesian hierarchical models using Gibbs sampling that aims for +the same functionality as classic \proglang{BUGS}. \proglang{JAGS} is developed to work closely together with \R{} and +the \pkg{coda} package. + +%% Revision 2005-01-10 end + +In this paper, we give two examples, involving educational testing experiments in schools (cf.~Section~\ref{School}), +and incidence of childhood leukaemia depending on benzene emissions (cf.~Section~\ref{Leukaemia}). Details on the +functions of \RO{} are given in Section~\ref{Programming}. These functions automatically write the data and a +script in a format readable by \OpenBUGS{} for processing in batch mode, and call \OpenBUGS{} from \R{}. After the +\OpenBUGS{} process has finished, it is possible either to read the resulting data into \R{} by the package itself +or to use the facilities of the \pkg{coda} package for further analyses of the output. In Section~\ref{Example2}, +we demonstrate how to apply the functions provided by \RO{} on the examples' data, and how to analyze the output +both with package \pkg{coda} and with \RO{}'s methods to \verb+plot()+ and \verb+print()+ the output. + + +\section{Examples}\label{Examples} +In this Section, we introduce two examples which will be continued in Section~\ref{Example2}. + +\subsection{Schools data}\label{School} +The Scholastic Aptitude Test (SAT) measures the aptitude of high-schoolers in order to help colleges to make +admissions decisions. It is divided into two parts, verbal (SAT-V) and mathematical (SAT-M). +Our data comes from the SAT-V (Scholastic Aptitude Test-Verbal) on eight different high schools, from an experiment conducted in the late 1970s. +SAT-V is a standard multiple choice test administered by the Educational Testing Service. +This Service was interested in the effects of coaching programs for each of the selected schools. + +The study included coached and uncoached pupils, about sixty in each of the eight different schools; see +\cite{Rubin:1981}. All of them had already taken the PSAT (Preliminary SAT) which results were used as covariates. +%Even if the test is constructed to be resistant to short-term +%efforts directed specifically toward improving test performance, each of the schools is successful at increasing +%SAT scores. +For each school, the estimated treatment effect and the standard error of the effect estimate are given. +These are calculated by an analysis of covariance adjustment appropriate for a completely randomized experiment +\citep{Rubin:1981}. This example was analyzed using a hierarchical normal model in \cite{Rubin:1981} and +\citeauthor{Gelman:2003} (\citeyear{Gelman:2003}, Section 5.5). + +\subsection{Leukaemia registration data}\label{Leukaemia} +Spatial data usually arises on different, non-nesting spatial scales. One example is childhood leukaemia +registration data analyzed by \cite{Best;Cockings;Bennett;Wakefield;Elliot:2001} +using ecologic regression. Data are given for Greater London bounded by the M25 orbital motorway. +%% Revision 2005-01-10 start +The data are not available as an example in \RO{} but we use the example here +to illustrate +alternative calls to the \verb+bugs()+ function and output analysis using the \pkg{coda} package. +%% Revision 2005-01-10 end + +The observed number of leukaemia cases among children under 15 years old is given at ward level. Census wards are +administrative areas containing approximately 5000 to 10\,000 people. Central London is divided into 873 wards. The +number of incident cases of leukaemia in children is available from 1985 until 1996 from the Office of National +Statistics and the Thames Cancer Registry. A plot of these numbers is given in Figure~\ref{observed}. + +\begin{figure} +\begin{center} +\includegraphics[width=0.85\textwidth]{countssw} +\caption{\label{observed}Observed number of cases of childhood leukaemia in 1985--1996} +\end{center} +\end{figure} + +Additionally, the number of expected cases (cf.~Fig.~\ref{expected}) is calculated on the same +resolution using population numbers for different age-sex-strata and the national leukaemia +rate for the corresponding strata, for details see \cite{Best;Cockings;Bennett;Wakefield;Elliot:2001}. + +\begin{figure} +\begin{center} +\includegraphics[width=0.85\textwidth]{expectedsw} +\caption{\label{expected}Expected number of cases of childhood leukaemia in 1985--1996}%, as obtained from a simple demographic model} +\end{center} +\end{figure} + +It is assumed that benzene emissions have an effect on the incidence rate of leukaemia. Benzene emission rates are +available in tonnes per year from an atmospheric emissions inventory for London +\citep{Buckingham;Clewley;Hutchinson;Sadler;Shah:1997} produced by the London Research Centre. They are provided +at 1km $\times$ 1km grid cells, giving 2132 grid cells in total. +Their spatial distribution is shown in Figure~\ref{benzene}. + +\begin{figure} +\begin{center} +\includegraphics[width=0.9\textwidth]{benzolsw} +\caption{\label{benzene}Benzene emissions in tonnes per year} +\end{center} +\end{figure} + +For further details on the data see \cite{Best;Cockings;Bennett;Wakefield;Elliot:2001}. + +We model these data by Poisson-Gamma models introduced by \cite{Best;Ickstadt;Wolpert:2000} using \OpenBUGS{}. +A linking matrix containing information which grid cell belongs to which ward +and to which amount is required. This matrix is calculated using \R{}. +Unfortunately, \OpenBUGS{} does not support a list format such as directly produced by \R{}. +Therefore, the data must be provided as a matrix with 2132 rows and 873 columns (or vice versa). +Most of the entries of this matrix are zeroes, but using \verb+dump()+ to export it from \R{} +yields in a file size of 14.2~MB. +Unfortunately, opening a file of such size really slows \OpenBUGS{} down, +and it was not even possible on some of our PCs. +Importing data written by our \RO{} package does not make any problems using the batch mode, +probably due to memory management issues in \OpenBUGS{}. + + +\section{Implementation}\label{Programming} +The implementation of the \RO{} package is straightforward. +The ``main'' function \verb+bugs()+ is intended to be called by the user. +In principle, it is a wrapper for several other functions called therein step by step as follows: +\begin{enumerate} + \item \verb+bugs.data.inits()+ writes the data files \file{data.txt}, and \file{inits1.txt}, \file{inits2.txt}, ... + into the working directory. These files will be used by \OpenBUGS{} during batch processing. + + In particular, input for \OpenBUGS{} must not exceed a certain number of digits. + Moreover, it needs an \verb+E+ instead of an \verb+e+ in scientific notation. + Scientific notation is particularly desirable because of the ``number of digits'' limitation. + The default (\verb+digits = 5+) is to, e.g., reformat the number \verb+123456.789+ to \verb@1.23457E+05@. + \item \verb+bugs.script()+ writes the file \file{script.txt} that is used by \OpenBUGS{} for batch processing. + \item \verb+bugs.run()+ updates the lengths of the adaptive phases in the \WinBUGS{} registry + (using a function \verb+bugs.update.settings()+), + calls \WinBUGS{}, and runs it in batch mode with \file{script.txt}. + \item \verb+bugs.sims()+ is only called if the argument \verb+codaPkg+ has been set to \verb+FALSE+ (the default). + Otherwise \verb+bugs()+ returns the filenames of stored data. These can, for example, + be imported by package \pkg{coda} (see the example in Section~\ref{Leukaemia2}, page~\pageref{codaexample}), + which provides functions for convergence diagnostics, + calculation of Monte Carlo estimates, trace plots, and so forth. + + The function \verb+bugs.sims()+ reads simulations from \OpenBUGS{} into \R{} (not necessarily called by \verb+bugs()+ + itself), formats them, + monitors convergence, performs convergence checks, and computes medians and quantiles. + It also prepares the output for \verb+bugs()+ itself. +\end{enumerate} +These functions are not intended to be called by the user directly. +Arguments are passed from \verb+bugs()+ to the other functions, if appropriate. +A shortened help file of \verb+bugs()+ listing all arguments is given in Appendix~\ref{Doc}; +for the full version type \verb+?bugs+ in \R{} after having installed and loaded the package \RO{} +(see Section~\ref{Introduction}). + +%\newpage +As known from \OpenBUGS{}, one must specify the \verb+data+ in form of a list, with list names equal to the names +of data in the corresponding \OpenBUGS{} model. Alternatively, it is possible to specify a vector or list of names +(of mode \verb+character+). In that case objects of that names are looked for in the environment in which +\verb+bugs()+ has been called (usually that is the user's Workspace, \verb+.GlobalEnv+). +%% Revision 2005-01-10 start +If data have already been written in a file called \file{data.txt} to the working directory, +it is possible to specify \verb+data = "data.txt"+. +%% Revision 2005-01-10 end +One will usually want to supply initial values. +This can be done either in the form of a function \verb+inits()+ that creates these values, so that +different chains can be automatically initialized at different points (see Section \ref{School2}), or by specifying them +directly (see Section \ref{Leukaemia2}). +If \verb+inits()+ is not specified, +\verb+bugs()+ just uses the starting values created by \OpenBUGS{}; but in practice \OpenBUGS{} can crash when +reasonable initial values are not specified, and so we recommend constructing a simple \verb+inits()+ function to +simulate reasonable starting points \cite[Section C.2]{Gelman:2003}. It is also necessary to specify which +parameters should be saved for monitoring by specifying \verb+parameters.to.save+. + +The user might also want to change the defaults for the length of the burn-in (\verb+n.burnin+, which defaults to half the length of the chain) +period for every MCMC run and the number of iterations (\verb+n.iter+, default value 3) +that are used to calculate Monte Carlo estimates. +%SS: Achtung: n.iter=n.burn.in + length of stored chain! +The specification of a thinning parameter (\verb+n.thin+) is possible as well; this is useful when the number of parameters is large, to keep the saved output to a reasonably-sized R object. + +By setting the argument \verb+debug = TRUE+, +\OpenBUGS{} remains open after the run. +This way it is possible to find errors in the code or the data structure, +or even to work with that software as in a usual run. This feature is not +available with Linux execution. + +It is possible to run one or more Markov chains. +The number of chains (\verb+n.chains+) must be specified together with the chains' initial values (\verb+inits+). +If more than one Markov chain is requested and \verb+codaPkg+ is set to \verb+FALSE+, the convergence diagnostic +$\hat{R}$ \citep{Brooks;Gelman:1998} is calculated by \verb+bugs.sims()+ for each of the saved parameters. + +%% Revision 2005-01-10 start +Since the communication between \OpenBUGS{} and \R{} is based on files, +rather huge files will be saved in the working directory by the \verb+bugs()+ call, +either files to be read in by \verb+bugs()+ itself, or by the \pkg{coda} package. +The user might want to delete those files after the desired contents has been imported into \R{}, +and save those objects, e.g., as compressed \R{} data files. +%% Revision 2005-01-10 end + +The function \verb+bugs()+ returns a rather complex object of class \verb+bugs+, +if called with argument \verb+codaPkg = FALSE+. +In order to look at the structure of such an object, type \verb+str(objectname)+. +For convenience, \RO{} provides methods corresponding to class \verb+bugs+ for +the generic functions \verb+print()+ and \verb+plot()+. + +So that user will not be overwhelmed with information; summaries of the output are provided by the +\verb+print()+ method. That is, some parameters of the \verb+bugs()+ call are summarized, and mean, +standard deviation, several quantiles of the parameters and convergence diagnostics based on \cite{Gelman;Rubin:1992} +are printed. See the example in +Section~\ref{School2}, page~\pageref{schoolssim}, for a typical output. As with \cite{Spiegelhalter;Best;Carlin;vdLinde:2002}, +%\pagebreak + the DIC computed by \verb+bugs.sims()+ is defined as the posterior mean +of the deviance plus $p_D$, the estimated effective number of parameters in the posterior distribution. We define +$p_D$ as half the posterior variance of the deviance and estimate it as half the average of the within-chain +variances of the deviance.\footnote{In contrast, \cite{Spiegelhalter;Best;Carlin;vdLinde:2002}, + and OpenBUGS, define $p_D$ as the +posterior mean of the deviance evaluated at the posterior mean of the parameter values. We cannot use that +definition because the deviance function is not available to our program, which calls \OpenBUGS{} from the +``outside''. Both definitions of $p_D$---ours and that introduced by \cite{Spiegelhalter;Best;Carlin;vdLinde:2002}---can be +derived from the asymptotic $\chi^2$ distribution of the deviance relative to its minimum \citep[Section 6.7]{Gelman:2003}. +We make no claim that our measure of $p_D$ is superior to that of \cite{Spiegelhalter;Best;Carlin;vdLinde:2002}; +we choose this measure purely because it is computationally possible given what is available to us from the \OpenBUGS{} output.} + + +The \verb+plot()+ for objects of class \verb+bugs+ +provides information condensed in some plots conveniently arranged within the same graphics device. +For an example, see Figure~\ref{plot} in Section~\ref{School2}. It is intended to adapt this function to work with MCMC output in general, even if obtained from software other than OpenBUGS. + + + +\section{Examples continued}\label{Example2} +The Examples introduced in Section~\ref{Example2} are continued in this Section. +We apply the functions provided by \RO{} +to the examples' data and analyze the output. + +\subsection{Schools data}\label{School2} +Schools example data (see Section~\ref{School}) are available with the \RO{} package: +\begin{Code} + > data(schools) + > schools + school estimate sd + 1 A 28.39 14.9 + 2 B 7.94 10.2 + 3 C -2.75 16.3 + 4 D 6.82 11.0 + 5 E -0.64 9.4 + 6 F 0.63 11.4 + 7 G 18.01 10.4 + 8 H 12.16 17.6 +\end{Code} +For modeling these data, we use a hierarchical model as proposed by \citeauthor{Gelman:2003} (\citeyear{Gelman:2003}, Section 5.5). +We assume a normal distribution for the observed estimate for each school with +mean \verb+theta+ and inverse-variance \verb+tau.y+. +The inverse-variance is given as $1/\verb+sigma.y+^{2}$ and its prior distribution is uniform on (0,1000). For the mean +\verb+theta+, we employ another normal distribution with mean \verb+mu.theta+ and inverse-variance \verb+tau.theta+. For +their prior distributions, see the following \OpenBUGS{} code: + + +\begin{Code} + model { + 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) + } +\end{Code} +This model must be stored in a separate file, e.g.~\file{schools.bug}\footnote{Emacs Speaks Statistics (ESS) +by \cite{rossini04}, a package available with Gnu Emacs \citep{stallmann99}, +recognizes and properly formats Bugs model files that have the .bug extension.}, +in an appropriate directory, say \path{c:/schools/}. +In \R{} the user must prepare the data inputs the \verb+bugs()+ function needs. +This can be a list containing the name of each data vector, e.g. +\begin{Code} + > J <- nrow(schools) + > y <- schools$estimate + > sigma.y <- schools$sd + > data <- list ("J", "y", "sigma.y") +\end{Code} +Using these data and the model file, we can run an MCMC simulation to get estimates for \verb+theta+, +\verb+mu.theta+ and \verb+sigma.theta+. Before running, the user must decide how many chains to be run +(\verb+n.chain = 3+) for how many iterations (\verb+n.iter = 1000+). +If the length of burn-in is not specified, \verb+n.burnin = floor(n.iter/2)+ is used, that is, 500 in this example. +Additionally, the user must specify initial values for the chains, for example by writing a function. This can be done by +\begin{Code} + > inits <- function(){ + + list(theta = rnorm(J, 0, 100), mu.theta = rnorm(1, 0, 100), + + sigma.theta = runif(1, 0, 100)) + + } +\end{Code} +Now, the user can start the MCMC simulation by typing +\begin{Code} + > schools.sim <- bugs(data, inits, model.file = "c:/schools/schools.bug", + + parameters = c("theta", "mu.theta", "sigma.theta"), + + n.chains = 3, n.iter = 1000) +\end{Code} +in \R{}.\label{schoolssim} +For other available arguments, see Appendix \ref{Doc}. + +The results in objects \verb+schools.sim+ can conveniently be printed by \verb+print(schools.sim)+. +The generic function \verb+print()+ calls the print method for an object of class \verb+bugs+ +provided by \RO{}. +For this example, you will get something like + +\small +\begin{Code} + > print(schools.sim) + Inference for Bugs model at "c:/schools/schools.bug" + 3 chains, each with 1000 iterations (first 500 discarded) + n.sims = 1500 iterations saved + mean sd 2.5% 25% 50% 75% 97.5% Rhat n.eff + theta[1] 11.1 9.1 -3.0 5.0 10.0 16.0 31.8 1.1 39 + theta[2] 7.6 6.6 -4.7 3.3 7.8 11.6 21.1 1.1 42 + theta[3] 5.7 8.4 -12.5 0.6 6.1 10.8 21.8 1.0 150 + theta[4] 7.1 7.0 -6.6 2.7 7.2 11.5 21.0 1.1 42 + theta[5] 5.1 6.8 -9.5 0.7 5.2 9.7 18.1 1.0 83 + theta[6] 5.7 7.3 -9.7 1.0 6.2 10.2 20.0 1.0 56 + theta[7] 10.4 7.3 -2.1 5.3 9.8 15.3 25.5 1.1 27 + theta[8] 8.3 8.4 -6.6 2.8 8.1 12.7 26.2 1.0 64 + mu.theta 7.6 5.9 -3.0 3.7 8.0 11.0 19.5 1.1 35 + sigma.theta 6.7 5.6 0.3 2.8 5.1 9.2 21.2 1.1 46 + deviance 60.8 2.5 57.0 59.1 60.2 62.1 66.6 1.0 170 + pD = 3 and DIC = 63.8 (using the rule, pD = var(deviance)/2) + + For each parameter, n.eff is a crude measure of effective sample size, + and Rhat is the potential scale reduction factor (at convergence, Rhat=1). + DIC is an estimate of expected predictive error (lower deviance is better). +\end{Code} +\normalsize +Additionally, the user can generate a plot of the results by typing \verb+plot(schools.sim)+. +The resulting plot is given in Figure~\ref{plot}. +\begin{figure}[t] +\begin{center} +\fbox{ +\includegraphics[width=0.9\textwidth]{plot} +} \caption{\label{plot}Plot produced by \RO{} package for the schools example. } +\end{center} +\end{figure} +In this plot, the left column shows a quick +summary of inference and convergence ($\widehat{R}$ is close to 1.0 for all parameters, indicating good mixing of +the three chains and thus approximate convergence); and the right column shows inferences for each set of +parameters. As can be seen in the right column, \RO{} uses the parameter names in \OpenBUGS{} to structure the +output into scalar, vector, and arrays of parameters, in addition to storing the parameters as a long vector. + +For the interpretation of these results see \citeauthor{Gelman:2003} (\citeyear{Gelman:2003}, Section 5.5). + +\subsection{Leukaemia registration data}\label{Leukaemia2} +The leukaemia registration data (see Section \ref{Leukaemia}) are used to show data modeling and output reading +into \R{} using the \pkg{coda} package. A simple model for these data looks as follows: +\begin{Code} +model{ + beta.0 ~ dgamma(a.0, tau.0) + beta.benz ~ dgamma(a.benz, tau.benz) + a.0 <- 0.575 + tau.0 <- a.0*2 + a.benz <- 0.575 + tau.benz <- a.benz*2 +\end{Code} +\clearpage +\begin{Code} + for (i in 1:I) + { + count[i] ~ dpois(lambda[i]) + lambda[i] <- p[i]*expect[i] + for (j in 1:J) + { + prop[j,i] <- gamma[j,i]*(benz[j] - benzbar) + } + p[i]<- beta.0 + beta.benz*sum(prop[,i]) + } + } +\end{Code} +Here \verb+count+ denotes the number of observed incidences of childhood leukaemia in ward~\verb+i+. These are +assumed to be Poisson distributed with mean \verb+lambda+ depending on the number of expected cases \verb+expect+ +in ward \verb+i+ and an area-specific risk rate \verb+p+. For calculation of this area specific risk rate we use +an intercept \verb+beta.0+ and a term depending on the weighted sum of benzene emissions \verb+benz+ in each grid +cell \verb+j+. The weights are chosen proportional to the amount of area that ward \verb+i+ and grid cell \verb+j+ have +in common. + +In \R{} we can define all these data and then initialize the model. The data needed for this example are +\begin{description} +\item[\tt{benzbar}:] arithmetic mean of all benzene values, +\item[\tt{benz}:] a vector containing benzene emissions of all 2132 grid cells, +\item[\tt{expect}:] expected number of cases of childhood leukaemia in each of the 873 wards, +\item[\tt{count}:] observed number of childhood leukaemia in these wards, +\item[\tt{gamma}:] a $2132\times 873$ matrix containing the amount of area each grid cell and each ward have in common, +\item[\tt{J}:] total number of grid cells, i.e.~2132, and +\item[\tt{I}:] total number of ward cells, i.e.~873. +\end{description} +The parameters we want to store are regression coefficients \verb+beta.0+ and \verb+beta.benz+ as well as +\verb+p+, the area specific relative risk compared to the reference rate. This reference rate was used to +calculate the expected number of cases in each ward. + +Since we want to use the \pkg{coda} package for reading the data into \OpenBUGS{}, we specify \verb+codaPkg = TRUE+ +in the \verb+bugs()+ call: +\begin{Code} + > data <- list(benzbar = mean(benz), benz = benz, expect = expect, + + count = count, gamma = gamma, J = J, I = I) + > parameters <- c("beta.0", "beta.benz", "p") + > inits1 <- list(beta.0 = 1, beta.benz = 1) + > inits2 <- list(beta.0 = 0.5, beta.benz = 0.5) + > inits <- list(inits1, inits2) + > model <- bugs(data, inits, parameters, model.file = "c:/model.bug", + + n.chains = 2, n.iter = 8000, n.burnin = 5000, n.thin = 1, + + codaPkg = TRUE ) +\end{Code} + +\clearpage +Starting with, e.g.,\label{codaexample} +\begin{Code} + > library("coda") + > codaobject <- read.bugs(model) + > plot(codaobject) +\end{Code} +it is now possible to use the \pkg{coda} package for output analyses. + + +\section*{Acknowledgments} +The work of Uwe Ligges has been supported by the Deutsche Forschungsgemeinschaft, +Sonderforschungsbereich 475. +The work of Andrew Gelman has been supported by the U.S. National Science Foundation. + +\bibliography{literatur} + +\clearpage +\begin{appendix} +\section[Help page for the function bugs()]{Help page for the function \code{bugs()}\label{Doc}} +\small +This help page has been shortened. +\input{bugs} +\end{appendix} +\end{document} Deleted: trunk/R2OpenBUGS/inst/doc/R2WinBUGS.Rnw =================================================================== --- trunk/R2OpenBUGS/inst/doc/R2WinBUGS.Rnw 2010-08-07 19:37:04 UTC (rev 164) +++ trunk/R2OpenBUGS/inst/doc/R2WinBUGS.Rnw 2010-08-10 02:53:35 UTC (rev 165) @@ -1,506 +0,0 @@ -%\VignetteIndexEntry{R2WinBUGS} -\documentclass{Z} -\usepackage{RdRW,thumbpdf} -\newcommand{\WinBUGS}{{\proglang{WinBUGS}}{}} -\newcommand{\RW}{{\pkg{R2WinBUGS}}{}} -\renewcommand{\R}{{\proglang{R}}{}} -\setlength{\textheight}{23.5cm} - -\title{\RW{}:\protect\linebreak A Package for Running \WinBUGS{} from \R{}} -\author{Sibylle Sturtz\thanks{\email{st...@st...}}\\Fachbereich Statistik\\Universit\"at Dortmund\\Germany - \And - Uwe Ligges\thanks{\email{li...@st...}}\\Fachbereich Statistik\\Universit\"at Dortmund\\Germany - \And - Andrew Gelman\thanks{\email{ge...@st...}}\\Department of Statistics\\Columbia University\\USA -} -\Plainauthor{Sibylle Sturtz, Uwe Ligges, Andrew Gelman} -\Plaintitle{R2WinBUGS: A Package for Running WinBUGS from R} - -\Abstract{ -The \RW{} package provides convenient functions to call \WinBUGS{} from \R{}. It -automatically writes the data and scripts in a format readable by \WinBUGS{} for processing in batch mode, which -is possible since version 1.4. After the \WinBUGS{} process has finished, it is possible either to read the -resulting data into \R{} by the package itself---which gives a compact graphical summary of inference and -convergence diagnostics---or to use the facilities of the \pkg{coda} package for further analyses of the -output. Examples are given to demonstrate the usage of this package. -} - -\Keywords{\R{}, \WinBUGS{}, interface, MCMC} -\Plainkeywords{R, WinBUGS, interface, MCMC} - -\begin{document} -An earlier version of this vignette has been published by the Journal of Statistical Software:\\ -Sturtz S, Ligges U, Gelman A (2005): -``\RW{}: A Package for Running \WinBUGS{} from \R{}.'' -{\em Journal of Statistical Software}, 12(3), 1--16. - - -\section{Introduction}\label{Introduction} -The usage of Markov chain Monte Carlo (MCMC) methods became very popular within the last decade. \WinBUGS{} -\citep[\textbf{B}ayesian inference \textbf{U}sing \textbf{G}ibbs \textbf{S}ampling, ][] -{Spiegelhalter;Thomas;Best:2003} is a popular software for analyzing complex statistical models using MCMC -methods. This software uses Gibbs sampling \citep{Geman;Geman:1984,Gelfand;Smith:1990,Casella;George:1992} and the -Metropolis algorithm \citep{Metropolis;Rosenbluth;Rosenbluth;Teller;Teller:1953} -to generate a Markov chain by sampling from full conditional -distributions. -The \WinBUGS{} software is available for free -at \url{http://www.mrc-bsu.cam.ac.uk/bugs/}. -An introduction to MCMC methods is given in \cite{Gilks;Richardson;Spiegelhalter:1996}. - -Using \WinBUGS{}, the user must specify the model to run, and to load data and initial values for a specified -number of Markov chains. Then it is possible to run the Markov chain(s) and to save the results for the parameters -the user is interested in. Summary statistics of these data, convergence diagnostics, kernel estimates -etc.\ are available as well. -Nevertheless, some users of this software might be interested in saving the output and reading it into \R{} -\citep{RCore:2004} for further analyses. -\WinBUGS{} 1.4 comes with the ability to run the software in batch mode using scripts. - -The \RW{} package makes use of this feature and provides the tools to call \WinBUGS{} -directly after data manipulation in \R{}. Furthermore, it is possible to -work with the results after importing them back into \R{} again, for example to create posterior predictive simulations or, more generally, graphical displays of data and posterior simulations \citep{gelman:2004}. -Embedding in R can also be useful for frequently changed data or processing a bunch of data sets, -because it is much more convenient to use some \R{} functions (possibly within a loop) -rather than using ``copy \& paste'' to update data in \WinBUGS{} each time; however difficulties have been encountered in this area because both \R{} and \WinBUGS{} can lock up RAM in the Windows operating system. - -\R{} is a ``language for data analysis and graphics'' and an open source and -freely available statistical software package implementing that language, see \url{http://www.R-project.org/}. -Historically, \R{} is an implementation of the award-winning \proglang{S} -language and system \citep{becker:1984r,becker:1988r,chambers:1992,chambers:1998}. -\R{} and \RW{} are available from \emph{CRAN} (Comprehensive \R{} Archive Network), -i.e., \url{http://CRAN.R-Project.org} or one of its mirrors. -\RW{} could be ported to the commercial \proglang{S} implementation -\textsc{S-Plus}. Minor adaptions would be needed since \textsc{S-Plus} -lacks some of \R{}'s functions and capabilities. -If an internet connection is available, \RW{} can be installed by typing -\verb+install.packages("R2WinBUGS")+ at the \R{} command prompt. -Do not forget to load the package with \verb+library("R2WinBUGS")+. - -The package \pkg{coda} by \cite{Plummer;Best;Cowles;Vines:2004} is very useful for the analysis of \WinBUGS{}' -output, the reader might want to install this package as well. The CRAN package \pkg{boa} (Bayesian Output -Analysis Program) by \cite{Smith:2004} has similar aims. -\proglang{JAGS} (Just Another Gibbs Sampler) -by \cite{Plummer:2003} is a program for analysis of Bayesian hierarchical models using Gibbs sampling that aims for -the same functionality as classic \proglang{BUGS}. \proglang{JAGS} is developed to work closely together with \R{} and -the \pkg{coda} package. - -%% Revision 2005-01-10 start -A new and completely revised version of WinBUGS called \proglang{OpenBUGS} \citep{Spiegelhalter;Thomas;Best;Lunn:2004} -was lately published under the terms of the GPL. -\proglang{OpenBUGS} is also expected to run under Linux. -It provides a much more flexible API on which ``BRugs'' is based including -a dynamic link library, incorporating a component loader -that allows \R{} to make use of \proglang{OpenBUGS} components. -OpenBUGS is still in development and suffers frequent crashes. -As OpenBUGS becomes more reliable, -it is planned to merge ``BRugs'' and \RW{} into one \R{} package. -%% Revision 2005-01-10 end - -For other packages and projects on spatial statistics -related to \R{}, follow the link to ``\R{} spatial projects'' at CRAN. - -In this paper, we give two examples, involving educational testing experiments in schools (cf.~Section~\ref{School}), -and incidence of childhood leukaemia depending on benzene emissions (cf.~Section~\ref{Leukaemia}). Details on the -functions of \RW{} are given in Section~\ref{Programming}. These functions automatically write the data and a -script in a format readable by \WinBUGS{} for processing in batch mode, and call \WinBUGS{} from \R{}. After the -\WinBUGS{} process has finished, it is possible either to read the resulting data into \R{} by the package itself -or to use the facilities of the \pkg{coda} package for further analyses of the output. In Section~\ref{Example2}, -we demonstrate how to apply the functions provided by \RW{} on the examples' data, and how to analyze the output -both with package \pkg{coda} and with \RW{}'s methods to \verb+plot()+ and \verb+print()+ the output. - - -\section{Examples}\label{Examples} -In this Section, we introduce two examples which will be continued in Section~\ref{Example2}. - -\subsection{Schools data}\label{School} -The Scholastic Aptitude Test (SAT) measures the aptitude of high-schoolers in order to help colleges to make -admissions decisions. It is divided into two parts, verbal (SAT-V) and mathematical (SAT-M). -Our data comes from the SAT-V (Scholastic Aptitude Test-Verbal) on eight different high schools, from an experiment conducted in the late 1970s. -SAT-V is a standard multiple choice test administered by the Educational Testing Service. -This Service was interested in the effects of coaching programs for each of the selected schools. - -The study included coached and uncoached pupils, about sixty in each of the eight different schools; see -\cite{Rubin:1981}. All of them had already taken the PSAT (Preliminary SAT) which results were used as covariates. -%Even if the test is constructed to be resistant to short-term -%efforts directed specifically toward improving test performance, each of the schools is successful at increasing -%SAT scores. -For each school, the estimated treatment effect and the standard error of the effect estimate are given. -These are calculated by an analysis of covariance adjustment appropriate for a completely randomized experiment -\citep{Rubin:1981}. This example was analyzed using a hierarchical normal model in \cite{Rubin:1981} and -\citeauthor{Gelman:2003} (\citeyear{Gelman:2003}, Section 5.5). - -\subsection{Leukaemia registration data}\label{Leukaemia} -Spatial data usually arises on different, non-nesting spatial scales. One example is childhood leukaemia -registration data analyzed by \cite{Best;Cockings;Bennett;Wakefield;Elliot:2001} -using ecologic regression. Data are given for Greater London bounded by the M25 orbital motorway. -%% Revision 2005-01-10 start -The data are not available as an example in \RW{} but we use the example here -to illustrate -alternative calls to the \verb+bugs()+ function and output analysis using the \pkg{coda} package. -%% Revision 2005-01-10 end - -The observed number of leukaemia cases among children under 15 years old is given at ward level. Census wards are -administrative areas containing approximately 5000 to 10\,000 people. Central London is divided into 873 wards. The -number of incident cases of leukaemia in children is available from 1985 until 1996 from the Office of National -Statistics and the Thames Cancer Registry. A plot of these numbers is given in Figure~\ref{observed}. - -\begin{figure} -\begin{center} -\includegraphics[width=0.85\textwidth]{countssw} -\caption{\label{observed}Observed number of cases of childhood leukaemia in 1985--1996} -\end{center} -\end{figure} - -Additionally, the number of expected cases (cf.~Fig.~\ref{expected}) is calculated on the same -resolution using population numbers for different age-sex-strata and the national leukaemia -rate for the corresponding strata, for details see \cite{Best;Cockings;Bennett;Wakefield;Elliot:2001}. - -\begin{figure} -\begin{center} -\includegraphics[width=0.85\textwidth]{expectedsw} -\caption{\label{expected}Expected number of cases of childhood leukaemia in 1985--1996}%, as obtained from a simple demographic model} -\end{center} -\end{figure} - -It is assumed that benzene emissions have an effect on the incidence rate of leukaemia. Benzene emission rates are -available in tonnes per year from an atmospheric emissions inventory for London -\citep{Buckingham;Clewley;Hutchinson;Sadler;Shah:1997} produced by the London Research Centre. They are provided -at 1km $\times$ 1km grid cells, giving 2132 grid cells in total. -Their spatial distribution is shown in Figure~\ref{benzene}. - -\begin{figure} -\begin{center} -\includegraphics[width=0.9\textwidth]{benzolsw} -\caption{\label{benzene}Benzene emissions in tonnes per year} -\end{center} -\end{figure} - -For further details on the data see \cite{Best;Cockings;Bennett;Wakefield;Elliot:2001}. - -We model these data by Poisson-Gamma models introduced by \cite{Best;Ickstadt;Wolpert:2000} using \WinBUGS{}. -A linking matrix containing information which grid cell belongs to which ward -and to which amount is required. This matrix is calculated using \R{}. -Unfortunately, \WinBUGS{} does not support a list format such as directly produced by \R{}. -Therefore, the data must be provided as a matrix with 2132 rows and 873 columns (or vice versa). -Most of the entries of this matrix are zeroes, but using \verb+dump()+ to export it from \R{} -yields in a file size of 14.2~MB. -Unfortunately, opening a file of such size really slows \WinBUGS{} down, -and it was not even possible on some of our PCs. -Importing data written by our \RW{} package does not make any problems using the batch mode, -probably due to memory management issues in \WinBUGS{}. - - -\section{Implementation}\label{Programming} -The implementation of the \RW{} package is straightforward. -The ``main'' function \verb+bugs()+ is intended to be called by the user. -In principle, it is a wrapper for several other functions called therein step by step as follows: -\begin{enumerate} - \item \verb+bugs.data.inits()+ writes the data files \file{data.txt}, and \file{inits1.txt}, \file{inits2.txt}, ... - into the working directory. These files will be used by \WinBUGS{} during batch processing. - - In particular, input for \WinBUGS{} must not exceed a certain number of digits. - Moreover, it needs an \verb+E+ instead of an \verb+e+ in scientific notation. - Scientific notation is particularly desirable because of the ``number of digits'' limitation. - The default (\verb+digits = 5+) is to, e.g., reformat the number \verb+123456.789+ to \verb@1.23457E+05@. - \item \verb+bugs.script()+ writes the file \file{script.txt} that is used by \WinBUGS{} for batch processing. - \item \verb+bugs.run()+ updates the lengths of the adaptive phases in the \WinBUGS{} registry - (using a function \verb+bugs.update.settings()+), - calls \WinBUGS{}, and runs it in batch mode with \file{script.txt}. - \item \verb+bugs.sims()+ is only called if the argument \verb+codaPkg+ has been set to \verb+FALSE+ (the default). - Otherwise \verb+bugs()+ returns the filenames of stored data. These can, for example, - be imported by package \pkg{coda} (see the example in Section~\ref{Leukaemia2}, page~\pageref{codaexample}), - which provides functions for convergence diagnostics, - calculation of Monte Carlo estimates, trace plots, and so forth. - - The function \verb+bugs.sims()+ reads simulations from \WinBUGS{} into \R{} (not necessarily called by \verb+bugs()+ - itself), formats them, - monitors convergence, performs convergence checks, and computes medians and quantiles. - It also prepares the output for \verb+bugs()+ itself. -\end{enumerate} -These functions are not intended to be called by the user directly. -Arguments are passed from \verb+bugs()+ to the other functions, if appropriate. -A shortened help file of \verb+bugs()+ listing all arguments is given in Appendix~\ref{Doc}; -for the full version type \verb+?bugs+ in \R{} after having installed and loaded the package \RW{} -(see Section~\ref{Introduction}). - -%\newpage -As known from \WinBUGS{}, one must specify the \verb+data+ in form of a list, with list names equal to the names -of data in the corresponding \WinBUGS{} model. Alternatively, it is possible to specify a vector or list of names -(of mode \verb+character+). In that case objects of that names are looked for in the environment in which -\verb+bugs()+ has been called (usually that is the user's Workspace, \verb+.GlobalEnv+). -%% Revision 2005-01-10 start -If data have already been written in a file called \file{data.txt} to the working directory, -it is possible to specify \verb+data = "data.txt"+. -%% Revision 2005-01-10 end -One will usually want to supply initial values. -This can be done either in the form of a function \verb+inits()+ that creates these values, so that -different chains can be automatically initialized at different points (see Section \ref{School2}), or by specifying them -directly (see Section \ref{Leukaemia2}). -If \verb+inits()+ is not specified, -\verb+bugs()+ just uses the starting values created by \WinBUGS{}; but in practice \WinBUGS{} can crash when -reasonable initial values are not specified, and so we recommend constructing a simple \verb+inits()+ function to -simulate reasonable starting points \cite[Section C.2]{Gelman:2003}. It is also necessary to specify which -parameters should be saved for monitoring by specifying \verb+parameters.to.save+. - -The user might also want to change the defaults for the length of the burn-in (\verb+n.burnin+, which defaults to half the length of the chain) -period for every MCMC run and the number of iterations (\verb+n.iter+, default value 3) -that are used to calculate Monte Carlo estimates. -%SS: Achtung: n.iter=n.burn.in + length of stored chain! -The specification of a thinning parameter (\verb+n.thin+) is possible as well; this is useful when the number of parameters is large, to keep the saved output to a reasonably-sized R object. In the default setting, the chains are thinned enough so that approximately 1000 simulation draws are saved. - -By setting the argument \verb+debug = TRUE+, -\WinBUGS{} remains open after the run. -This way it is possible to find errors in the code or the data structure, -or even to work with that software as in a usual run. - -It is possible to run one or more Markov chains. -The number of chains (\verb+n.chains+) must be specified together with the chains' initial values (\verb+inits+). -If more than one Markov chain is requested and \verb+codaPkg+ is set to \verb+FALSE+, the convergence diagnostic -$\hat{R}$ \citep{Brooks;Gelman:1998} is calculated by \verb+bugs.sims()+ for each of the saved parameters. - -%% Revision 2005-01-10 start -Since the communication between \WinBUGS{} and \R{} is based on files, -rather huge files will be saved in the working directory by the \verb+bugs()+ call, -either files to be read in by \verb+bugs()+ itself, or by the \pkg{coda} package. -The user might want to delete those files after the desired contents has been imported into \R{}, -and save those objects, e.g., as compressed \R{} data files. -%% Revision 2005-01-10 end - -The function \verb+bugs()+ returns a rather complex object of class \verb+bugs+, -if called with argument \verb+codaPkg = FALSE+. -In order to look at the structure of such an object, type \verb+str(objectname)+. -For convenience, \RW{} provides methods corresponding to class \verb+bugs+ for -the generic functions \verb+print()+ and \verb+plot()+. - -So that user will not be overwhelmed with information; summaries of the output are provided by the -\verb+print()+ method. That is, some parameters of the \verb+bugs()+ call are summarized, and mean, -standard deviation, several quantiles of the parameters and convergence diagnostics based on \cite{Gelman;Rubin:1992} -are printed. See the example in -Section~\ref{School2}, page~\pageref{schoolssim}, for a typical output. As with \cite{Spiegelhalter;Best;Carlin;vdLinde:2002}, -%\pagebreak - the DIC computed by \verb+bugs.sims()+ is defined as the posterior mean -of the deviance plus $p_D$, the estimated effective number of parameters in the posterior distribution. We define -$p_D$ as half the posterior variance of the deviance and estimate it as half the average of the within-chain -variances of the deviance.\footnote{In contrast, \cite{Spiegelhalter;Best;Carlin;vdLinde:2002}, - and WinBUGS, define $p_D$ as the -posterior mean of the deviance evaluated at the posterior mean of the parameter values. We cannot use that -definition because the deviance function is not available to our program, which calls \WinBUGS{} from the -``outside''. Both definitions of $p_D$---ours and that introduced by \cite{Spiegelhalter;Best;Carlin;vdLinde:2002}---can be -derived from the asymptotic $\chi^2$ distribution of the deviance relative to its minimum \citep[Section 6.7]{Gelman:2003}. -We make no claim that our measure of $p_D$ is superior to that of \cite{Spiegelhalter;Best;Carlin;vdLinde:2002}; -we choose this measure purely because it is computationally possible given what is available to us from the \WinBUGS{} output.} - - -The \verb+plot()+ for objects of class \verb+bugs+ -provides information condensed in some plots conveniently arranged within the same graphics device. -For an example, see Figure~\ref{plot} in Section~\ref{School2}. It is intended to adapt this function to work with MCMC output in general, even if obtained from software other than WinBUGS. - - - -\section{Examples continued}\label{Example2} -The Examples introduced in Section~\ref{Example2} are continued in this Section. -We apply the functions provided by \RW{} -to the examples' data and analyze the output. - -\subsection{Schools data}\label{School2} -Schools example data (see Section~\ref{School}) are available with the \RW{} package: -\begin{Code} - > data(schools) - > schools - school estimate sd - 1 A 28.39 14.9 - 2 B 7.94 10.2 - 3 C -2.75 16.3 - 4 D 6.82 11.0 - 5 E -0.64 9.4 - 6 F 0.63 11.4 - 7 G 18.01 10.4 - 8 H 12.16 17.6 -\end{Code} -For modeling these data, we use a hierarchical model as proposed by \citeauthor{Gelman:2003} (\citeyear{Gelman:2003}, Section 5.5). -We assume a normal distribution for the observed estimate for each school with -mean \verb+theta+ and inverse-variance \verb+tau.y+. -The inverse-variance is given as $1/\verb+sigma.y+^{2}$ and its prior distribution is uniform on (0,1000). For the mean -\verb+theta+, we employ another normal distribution with mean \verb+mu.theta+ and inverse-variance \verb+tau.theta+. For -their prior distributions, see the following \WinBUGS{} code: - - -\begin{Code} - model { - 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) - } -\end{Code} -This model must be stored in a separate file, e.g.~\file{schools.bug}\footnote{Emacs Speaks Statistics (ESS) -by \cite{rossini04}, a package available with Gnu Emacs \citep{stallmann99}, -recognizes and properly formats Bugs model files that have the .bug extension.}, -in an appropriate directory, say \path{c:/schools/}. -In \R{} the user must prepare the data inputs the \verb+bugs()+ function needs. -This can be a list containing the name of each data vector, e.g. -\begin{Code} - > J <- nrow(schools) - > y <- schools$estimate - > sigma.y <- schools$sd - > data <- list ("J", "y", "sigma.y") -\end{Code} -Using these data and the model file, we can run an MCMC simulation to get estimates for \verb+theta+, -\verb+mu.theta+ and \verb+sigma.theta+. Before running, the user must decide how many chains to be run -(\verb+n.chain = 3+) for how many iterations (\verb+n.iter = 1000+). -If the length of burn-in is not specified, \verb+n.burnin = floor(n.iter/2)+ is used, that is, 500 in this example. -Additionally, the user must specify initial values for the chains, for example by writing a function. This can be done by -\begin{Code} - > inits <- function(){ - + list(theta = rnorm(J, 0, 100), mu.theta = rnorm(1, 0, 100), - + sigma.theta = runif(1, 0, 100)) - + } -\end{Code} -Now, the user can start the MCMC simulation by typing -\begin{Code} - > schools.sim <- bugs(data, inits, model.file = "c:/schools/schools.bug", - + parameters = c("theta", "mu.theta", "sigma.theta"), - + n.chains = 3, n.iter = 1000, - + bugs.directory = "c:/Program Files/WinBUGS14/") -\end{Code} -in \R{}.\label{schoolssim} The argument \verb+bugs.directory+ must point to the directory -where \WinBUGS{} has been installed. -For other available arguments, see Appendix \ref{Doc}. - -The results in objects \verb+schools.sim+ can conveniently be printed by \verb+print(schools.sim)+. -The generic function \verb+print()+ calls the print method for an object of class \verb+bugs+ -provided by \RW{}. -For this example, you will get something like - -\small -\begin{Code} - > print(schools.sim) - Inference for Bugs model at "c:/schools/schools.bug" - 3 chains, each with 1000 iterations (first 500 discarded) - n.sims = 1500 iterations saved - mean sd 2.5% 25% 50% 75% 97.5% Rhat n.eff - theta[1] 11.1 9.1 -3.0 5.0 10.0 16.0 31.8 1.1 39 - theta[2] 7.6 6.6 -4.7 3.3 7.8 11.6 21.1 1.1 42 - theta[3] 5.7 8.4 -12.5 0.6 6.1 10.8 21.8 1.0 150 - theta[4] 7.1 7.0 -6.6 2.7 7.2 11.5 21.0 1.1 42 - theta[5] 5.1 6.8 -9.5 0.7 5.2 9.7 18.1 1.0 83 - theta[6] 5.7 7.3 -9.7 1.0 6.2 10.2 20.0 1.0 56 - theta[7] 10.4 7.3 -2.1 5.3 9.8 15.3 25.5 1.1 27 - theta[8] 8.3 8.4 -6.6 2.8 8.1 12.7 26.2 1.0 64 - mu.theta 7.6 5.9 -3.0 3.7 8.0 11.0 19.5 1.1 35 - sigma.theta 6.7 5.6 0.3 2.8 5.1 9.2 21.2 1.1 46 - deviance 60.8 2.5 57.0 59.1 60.2 62.1 66.6 1.0 170 - pD = 3 and DIC = 63.8 (using the rule, pD = var(deviance)/2) - - For each parameter, n.eff is a crude measure of effective sample size, - and Rhat is the potential scale reduction factor (at convergence, Rhat=1). - DIC is an estimate of expected predictive error (lower deviance is better). -\end{Code} -\normalsize -Additionally, the user can generate a plot of the results by typing \verb+plot(schools.sim)+. -The resulting plot is given in Figure~\ref{plot}. -\begin{figure}[t] -\begin{center} -\fbox{ -\includegraphics[width=0.9\textwidth]{plot} -} \caption{\label{plot}Plot produced by \RW{} package for the schools example. } -\end{center} -\end{figure} -In this plot, the left column shows a quick -summary of inference and convergence ($\widehat{R}$ is close to 1.0 for all parameters, indicating good mixing of -the three chains and thus approximate convergence); and the right column shows inferences for each set of -parameters. As can be seen in the right column, \RW{} uses the parameter names in \WinBUGS{} to structure the -output into scalar, vector, and arrays of parameters, in addition to storing the parameters as a long vector. - -For the interpretation of these results see \citeauthor{Gelman:2003} (\citeyear{Gelman:2003}, Section 5.5). - -\subsection{Leukaemia registration data}\label{Leukaemia2} -The leukaemia registration data (see Section \ref{Leukaemia}) are used to show data modeling and output reading -into \R{} using the \pkg{coda} package. A simple model for these data looks as follows: -\begin{Code} -model{ - beta.0 ~ dgamma(a.0, tau.0) - beta.benz ~ dgamma(a.benz, tau.benz) - a.0 <- 0.575 - tau.0 <- a.0*2 - a.benz <- 0.575 - tau.benz <- a.benz*2 -\end{Code} -\clearpage -\begin{Code} - for (i in 1:I) - { - count[i] ~ dpois(lambda[i]) - lambda[i] <- p[i]*expect[i] - for (j in 1:J) - { - prop[j,i] <- gamma[j,i]*(benz[j] - benzbar) - } - p[i]<- beta.0 + beta.benz*sum(prop[,i]) - } - } -\end{Code} -Here \verb+count+ denotes the number of observed incidences of childhood leukaemia in ward~\verb+i+. These are -assumed to be Poisson distributed with mean \verb+lambda+ depending on the number of expected cases \verb+expect+ -in ward \verb+i+ and an area-specific risk rate \verb+p+. For calculation of this area specific risk rate we use -an intercept \verb+beta.0+ and a term depending on the weighted sum of benzene emissions \verb+benz+ in each grid -cell \verb+j+. The weights are chosen proportional to the amount of area that ward \verb+i+ and grid cell \verb+j+ have -in common. - -In \R{} we can define all these data and then initialize the model. The data needed for this example are -\begin{description} -\item[\tt{benzbar}:] arithmetic mean of all benzene values, -\item[\tt{benz}:] a vector containing benzene emissions of all 2132 grid cells, -\item[\tt{expect}:] expected number of cases of childhood leukaemia in each of the 873 wards, -\item[\tt{count}:] observed number of childhood leukaemia in these wards, -\item[\tt{gamma}:] a $2132\times 873$ matrix containing the amount of area each grid cell and each ward have in common, -\item[\tt{J}:] total number of grid cells, i.e.~2132, and -\item[\tt{I}:] total number of ward cells, i.e.~873. -\end{description} -The parameters we want to store are regression coefficients \verb+beta.0+ and \verb+beta.benz+ as well as -\verb+p+, the area specific relative risk compared to the reference rate. This reference rate was used to -calculate the expected number of cases in each ward. - -Since we want to use the \pkg{coda} package for reading the data into \WinBUGS{}, we specify \verb+codaPkg = TRUE+ -in the \verb+bugs()+ call: -\begin{Code} - > data <- list(benzbar = mean(benz), benz = benz, expect = expect, - + count = count, gamma = gamma, J = J, I = I) - > parameters <- c("beta.0", "beta.benz", "p") - > inits1 <- list(beta.0 = 1, beta.benz = 1) - > inits2 <- list(beta.0 = 0.5, beta.benz = 0.5) - > inits <- list(inits1, inits2) - > model <- bugs(data, inits, parameters, model.file = "c:/model.bug", - + n.chains = 2, n.iter = 8000, n.burnin = 5000, n.thin = 1, - + codaPkg = TRUE, bugs.directory = "c:/Program File... [truncated message content] |
From: <chr...@us...> - 2010-08-07 19:37:18
|
Revision: 164 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=164&view=rev Author: chris-jackson Date: 2010-08-07 19:37:04 +0000 (Sat, 07 Aug 2010) Log Message: ----------- New branch of BRugs with Linux support. Detailed description of changes in NEWS. Modified Paths: -------------- branches/linux/BRugs/DESCRIPTION branches/linux/BRugs/NAMESPACE branches/linux/BRugs/NEWS branches/linux/BRugs/R/bgr.point.R branches/linux/BRugs/R/dimensions.R branches/linux/BRugs/R/get.chain.R branches/linux/BRugs/R/info.node.R branches/linux/BRugs/R/internal.R branches/linux/BRugs/R/model.check.R branches/linux/BRugs/R/model.compile.R branches/linux/BRugs/R/model.inits.R branches/linux/BRugs/R/model.names.R branches/linux/BRugs/R/model.precision.R branches/linux/BRugs/R/model.setRN.R branches/linux/BRugs/R/plot.bgr.R branches/linux/BRugs/R/samples.coda.R branches/linux/BRugs/R/samples.correl.R branches/linux/BRugs/R/samples.get.beg.R branches/linux/BRugs/R/samples.get.end.R branches/linux/BRugs/R/samples.get.firstChain.R branches/linux/BRugs/R/samples.get.lastChain.R branches/linux/BRugs/R/samples.get.thin.R branches/linux/BRugs/R/samples.monitors.R branches/linux/BRugs/R/samples.sample.R branches/linux/BRugs/R/samples.set.beg.R branches/linux/BRugs/R/samples.set.end.R branches/linux/BRugs/R/samples.set.firstChain.R branches/linux/BRugs/R/samples.set.lastChain.R branches/linux/BRugs/R/samples.set.thin.R branches/linux/BRugs/R/samples.size.R branches/linux/BRugs/R/samples.stats.R branches/linux/BRugs/R/set.values.R branches/linux/BRugs/R/zzz.R branches/linux/BRugs/man/BRugs.Rd branches/linux/BRugs/man/BRugsFit.Rd branches/linux/BRugs/man/bgr.point.Rd branches/linux/BRugs/man/model.RN.Rd branches/linux/BRugs/man/set.values.Rd branches/linux/BRugs/src/Makevars branches/linux/BRugs/tests/BRugs.R branches/linux/BRugs/tests/examples.R branches/linux/BRugs/tests/functions.R Added Paths: ----------- branches/linux/BRugs/R/internal-linux.R branches/linux/BRugs/R/internal-win.R branches/linux/BRugs/exec/ branches/linux/BRugs/src/BugsHelper.c Removed Paths: ------------- branches/linux/BRugs/R/model.getRN.R branches/linux/BRugs/configure branches/linux/BRugs/configure.win Modified: branches/linux/BRugs/DESCRIPTION =================================================================== --- branches/linux/BRugs/DESCRIPTION 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/DESCRIPTION 2010-08-07 19:37:04 UTC (rev 164) @@ -2,11 +2,10 @@ Title: OpenBUGS and its R / S-PLUS interface BRugs Version: 0.6-0 Date: 2010-04-30 -Author: The Chief Software Bug is Andrew Thomas, with web assistance from Real Bug Bob O'Hara. Other members of the BUGS team are statisticians David Spiegelhalter, Nicky Best, Dave Lunn and Ken Rice. Dave Lunn has also made major contributions to the software development. R Code modified, extended and packaged for R by Uwe Ligges and Sibylle Sturtz. Some ideas taken from the R2WinBUGS package based on code by Andrew Gelman. With considerable contributions by Gregor Gorjanc <gre...@bf...>. +Author: OpenBUGS was developed by Andrew Thomas, Dave Lunn, David Spiegelhalter and Nicky Best. R Code modified, extended and packaged for R by Uwe Ligges and Sibylle Sturtz. Some ideas taken from the R2WinBUGS package based on code by Andrew Gelman. With considerable contributions by Gregor Gorjanc. Linux port of BRugs and other developments by Chris Jackson. Description: An R / S-PLUS package containing OpenBUGS and its R / S-PLUS interface BRugs. Maintainer: Uwe Ligges <li...@st...> Depends: R (>= 2.5.0), coda Archs: i386 -OS_type: windows License: GPL-2 URL: http://www.openbugs.info/ Modified: branches/linux/BRugs/NAMESPACE =================================================================== --- branches/linux/BRugs/NAMESPACE 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/NAMESPACE 2010-08-07 19:37:04 UTC (rev 164) @@ -1,4 +1,3 @@ -useDynLib(BRugs) importFrom(coda, mcmc, mcmc.list) export(BRugsFit, bugsData, bugsInits, buildMCMC, dicClear, dicSet, dicStats, @@ -6,7 +5,7 @@ infoMemory,infoModules,infoNodeValues,infoNodeMethods,infoNodeTypes, infoUpdatersbyName,infoUpdatersbyDepth, modelAdaptivePhase, modelCheck, modelCompile, modelData, -modelGenInits, modelGetRN, modelInits, modelIteration, +modelGenInits, modelInits, modelIteration, modelNames, modelPrecision, modelSaveState, modelSetAP, modelSetIts, modelSetOR, modelSetRN, modelUpdate, modelEnable, modelDisable, Modified: branches/linux/BRugs/NEWS =================================================================== --- branches/linux/BRugs/NEWS 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/NEWS 2010-08-07 19:37:04 UTC (rev 164) @@ -1,17 +1,75 @@ -Changes to BRugs: -===================== +CHANGES MADE FOR LINUX PORT OF BRugs -Update 0.6-0 -- Switch to new OpenBUGS (currently 3.1.0) -- 32-bit versions only +* A C program called BugsHelper is used to call the OpenBUGS shared + library on Linux via a system() call. With one call of BugsHelper, + any number of different OpenBUGS API commands can be run. The state + of the model is "internalized" on entry from a file in the temporary + directory, and "externalized" on exit. The source is in src/ and + the binary is installed into exec/. -Update 0.5-3 -- fix writeModel() again by going through parse tree now -- fix buildMCMC() to report right thinning parameters and keep all samples +* New function .OpenBUGS() to execute a sequence of OpenBUGS API + commands of possibly differing types (e.g. CmdInterpreter, + RealArray, Integer) with given arguments. On Windows, this is a + wrapper for the old method of calling C functions from the + dyn.load()-ed library. On Linux, this calls BugsHelper once. The + old .CmdInterpreter and related functions still have the same + interfaces, but work by calling .OpenBUGS(). +* Input and output from the OpenBUGS API on Linux is performed through + files input1.txt, output1.txt, input2.txt, output2.txt, ... in the + same /tmp/R*** directory as the buffer.txt file. The buffer.txt + file is used as before for messages from OpenBUGS. -Update 0.5-2 -- added seed argument to BRugsFit() -- fix writeModel() to work for separatly specified function body -- fix writeModel() to make larger numeric (particularly integer) values - in scientific notation work +* A set of global variables is stored in the options() list containing + the begin and end iterations, first and last chains, thin interval + and precision to calculate sample statistics. This is required + because the OpenBUGS Internalize / Externalize facility used by + BugsHelper does not save these variables, which are normally stored + in the OpenBUGS internal module SamplesEmbed. They are not saved + because OpenBUGS considers them to be part of the GUI state + (equivalent to the values typed in Inference->Samples...) rather + than the model state. These variables are reset when a new model is + checked and compiled. + +* As a result, all functions which compute sample statistics must + first call an API command which is returned by + .SamplesGlobalsCmd(node). This command updates the values stored in + SamplesEmbed using the values stored in options(). This ensures + that OpenBUGS knows about them before calculating sample statistics. + (Note this is still done on Windows where it is not necessary, but + there should be negligible overhead). The directly affected + functions are samplesCoda(), samplesSize(), samplesSample(), + samplesStats(), samplesCorrel(), plotBgr(). + +* .onLoad() in zzz.R initialises these global variables on Linux and + Windows. + +* The corresponding set/get functions are changed to read and write + these global variables instead of updating the values in + SamplesEmbed. + +* plotBGR() modified to use a single .OpenBUGS() call to return a list + of samples for each required iteration on the grid. bgrPoint() + takes a sample instead of a node and iteration. Using one + .OpenBUGS() call for each sample would be an order of magnitude + slower using the Linux helper program. Assume the extra memory + overhead, compared to the old method, is not a problem on Windows. + +* infoNodeValues() and SetValues() now read and write the values from + multiple chains, and work on scalars as well as vectors. + +* modelNames() modified to use a single .OpenBUGS call instead of + looping API commands over names in the model. + +* useDynLib(BRugs) removed from NAMESPACE. This is done in .OnLoad() + instead, to ensure that it is only used on Windows. + +* modelGetRN() removed, as the initial random number preset is not + saved by the Externalize facility. The random number state however + is saved and restored properly during the model run. There is no + need for the initial preset to be read by the user, as it does not + change as the model runs. + +* samplesCorrel() wasn't setting begin/end/thin etc. properly, since + the CorrelEmbed module doesn't use the values in SamplesEmbed. + These are now read from the variables in options(). Modified: branches/linux/BRugs/R/bgr.point.R =================================================================== --- branches/linux/BRugs/R/bgr.point.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/bgr.point.R 2010-08-07 19:37:04 UTC (rev 164) @@ -1,14 +1,9 @@ "bgrPoint" <- -function(node, iteration) -# Calculate the bgr statistic at iteration +function(sample) +# Calculate the bgr statistic given a sample concatenated over chains { - oldEnd <- samplesGetEnd() - on.exit(samplesSetEnd(oldEnd)) - samplesSetEnd(as.integer(iteration)) numChains <- getNumChains() - sampleSize <- samplesSize(node) - command <- "SamplesEmbed.SampleValues" - sample <- samplesSample(node) + sampleSize <- length(sample) lenChain <- sampleSize %/% numChains if (is.R()) dq <- quantile(sample, c(0.1, 0.9), names = FALSE) @@ -25,5 +20,5 @@ } n.delta <- n.delta / numChains bgr.stat <- d.delta / n.delta - return(c(iteration, n.delta, d.delta, bgr.stat)) + return(c(n.delta, d.delta, bgr.stat)) } Modified: branches/linux/BRugs/R/dimensions.R =================================================================== --- branches/linux/BRugs/R/dimensions.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/dimensions.R 2010-08-07 19:37:04 UTC (rev 164) @@ -5,9 +5,8 @@ nodeLabel <- as.character(node) if(!(nodeLabel %in% modelNames())) stop("node must be a variable name from the model") - command <- "BugsRobjects.SetVariable" - .C("CharArray", command, nchar(command), nodeLabel, nchar(nodeLabel), integer(1), PACKAGE="BRugs") - command <- "BugsRobjects.GetNumDimensions" - dimensions <- .Integer(command) - return(dimensions) + dimensions <- .OpenBUGS(c("BugsRobjects.SetVariable", "BugsRobjects.GetNumDimensions"), + c("CharArray", "Integer"), + list(nodeLabel, NA))[[2]] + dimensions } Modified: branches/linux/BRugs/R/get.chain.R =================================================================== --- branches/linux/BRugs/R/get.chain.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/get.chain.R 2010-08-07 19:37:04 UTC (rev 164) @@ -2,6 +2,5 @@ function() # Get chain field { - command<- "BugsEmbed.chain" - .Integer(command) + getOption("BRugsNextChain") } Modified: branches/linux/BRugs/R/info.node.R =================================================================== --- branches/linux/BRugs/R/info.node.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/info.node.R 2010-08-07 19:37:04 UTC (rev 164) @@ -3,16 +3,18 @@ # Get current value of node { nodeLabel <- as.character(nodeLabel) - command <- "BugsRobjects.SetVariable" - len <- nchar(command) - .C("CharArray", command, as.integer(len), nodeLabel, nchar(nodeLabel), integer(1), PACKAGE="BRugs") - command <- "BugsRobjects.GetSize" - nodeSize <- .Integer(command) + out <- .OpenBUGS(c("BugsRobjects.SetVariable", "BugsRobjects.GetSize"), + c("CharArray","Integer"), + list(nodeLabel, NA)) + nodeSize <- out[[2]] if(nodeSize == -1) stop(nodeLabel, " is not a node in BUGS model") - command <- "BugsRobjects.GetValues" - .C("RealArray", command, nchar(command), as.double(rep(NA, nodeSize)), - as.integer(nodeSize), integer(1), NAOK = TRUE, PACKAGE="BRugs")[[3]] + numChains <- getNumChains() + out <- .OpenBUGS(c("BugsRobjects.SetVariable", "BugsRobjects.GetValues"), + c("CharArray","RealArray"), + list(nodeLabel, double(nodeSize*numChains))) + values <- matrix(out[[2]], nrow=nodeSize, ncol=numChains) + values } infoNodeMethods <- function(nodeLabel) Added: branches/linux/BRugs/R/internal-linux.R =================================================================== --- branches/linux/BRugs/R/internal-linux.R (rev 0) +++ branches/linux/BRugs/R/internal-linux.R 2010-08-07 19:37:04 UTC (rev 164) @@ -0,0 +1,36 @@ +dquote <- function(x){ + paste("\"", x, "\"", sep="") +} + +.OpenBUGS.Linux <- function(cmds, cmdtypes, args) +{ + ncmds <- length(cmds) + if (ncmds > 99999) stop("Maximum number of OpenBUGS API commands exceeded") + tempDir <- getOption("BRugsTmpdir") + ## Don't want internalize/externalize to overwrite the command + ## output buffer, so redirect its output to a separate trash can. + trashDir <- paste(tempDir, "_trash", sep="") + extFile <- getOption("BRugsExtFile") + pkgPath <- searchpaths()[search()=="package:BRugs"] + bugsPath <- paste(pkgPath, "/exec/BugsHelper", sep="") + shcmd <- paste(bugsPath, dquote(tempDir), dquote(trashDir), dquote(extFile)) + for (i in 1:ncmds) { + if (cmdtypes[i] %in% c("CharArray","RealArray")) + cat(args[[i]], file=paste(tempDir, "/input",i,".txt", sep="")) + cmdtype <- match(cmdtypes[i], .OpenBUGS.cmdtypes) - 1 + shcmd <- paste(shcmd, dquote(cmds[i]), cmdtype) + } + res <- system(shcmd) + handleRes(res) + out <- vector(ncmds, mode="list") + for (i in 1:ncmds) { + if (cmdtypes[i] %in% c("Integer","CharArray","RealArray")) + out[[i]] <- scan(paste(tempDir,"/output",i,".txt",sep=""), + switch(cmdtypes[i], + "Integer" = integer(), + "CharArray" = character(), + "RealArray" = double()), + quiet=TRUE) + } + out +} Added: branches/linux/BRugs/R/internal-win.R =================================================================== --- branches/linux/BRugs/R/internal-win.R (rev 0) +++ branches/linux/BRugs/R/internal-win.R 2010-08-07 19:37:04 UTC (rev 164) @@ -0,0 +1,33 @@ +### Run a list of OpenBUGS API command strings + +.OpenBUGS.Windows <- function(cmds, cmdtypes, args) +{ + ncmds <- length(cmds) + out <- vector(ncmds, mode="list") + for (i in 1:ncmds) { + out[[i]] <- switch(cmdtypes[i], + "CmdInterpreter" = { + res <- .C("CmdInterpreter", cmds[i], nchar(cmds[i]), integer(1), PACKAGE = "BRugs") + handleRes(res[[3]]) + res + }, + "Integer" = { + values <- .C("Integer", cmds[i], nchar(cmds[i]), integer(1), integer(1), PACKAGE = "BRugs") + handleRes(values[[4]]) + as.integer(values[[3]]) + }, + "CharArray" = { + values <- .C("CharArray", cmds[i], nchar(cmds[i]), args[[i]], nchar(args[[i]]), integer(1), PACKAGE="BRugs") + handleRes(values[[5]]) + values[[3]] + }, + "RealArray" = { + values <- .C("RealArray", cmds[i], nchar(cmds[i]), args[[i]], length(args[[i]]), integer(1), PACKAGE="BRugs") + handleRes(values[[5]]) + values[[3]] + }) + + } + out +} + Modified: branches/linux/BRugs/R/internal.R =================================================================== --- branches/linux/BRugs/R/internal.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/internal.R 2010-08-07 19:37:04 UTC (rev 164) @@ -1,18 +1,40 @@ +### Functions to run a single OpenBUGS API command string + .CmdInterpreter <- function(command) -{ - command <- as.character(command) - res <- .C("CmdInterpreter", command, nchar(command), integer(1), PACKAGE = "BRugs") - handleRes(res[[3]]) - return(res) +{ + unlist(.OpenBUGS(command, "CmdInterpreter")) } .Integer <- function(command) { - values <- .C("Integer", command, nchar(command), integer(1), integer(1), PACKAGE = "BRugs") - handleRes(values[[4]]) - as.integer(values[[3]]) + unlist(.OpenBUGS(command, "Integer")) } +.CharArray <- function(command, arg) +{ + unlist(.OpenBUGS(command, "CharArray", arg)) +} + +.RealArray <- function(command, arg) +{ + unlist(.OpenBUGS(command, "RealArray", arg)) +} + + +.OpenBUGS.cmdtypes <- c("CmdInterpreter","Integer","CharArray","RealArray") + +.OpenBUGS <- function(cmds, cmdtypes=NULL, args=NULL) { + ncmds <- length(cmds) + if (is.null(cmdtypes)) cmdtypes <- rep("CmdInterpreter", ncmds) + if (is.null(args)) args <- as.list(rep(NA, ncmds)) + stopifnot(ncmds==length(cmdtypes)) + stopifnot(ncmds==length(args)) + switch(Sys.info()["sysname"], + "Linux" = .OpenBUGS.Linux(cmds, cmdtypes, args), + "Windows" = .OpenBUGS.Windows(cmds, cmdtypes, args), + stop("Only Linux and Windows are supported")) +} + handleRes <- function(res) { switch(res, @@ -20,3 +42,18 @@ stop("An OpenBUGS procedure was called with the wrong type of argument."), stop("An OpenBUGS procedure was called with the wrong signature.")) } + +.SamplesGlobalsCmd <- function(node){ + options.old <- options() + options(scipen=20) # don't pass numbers in scientific notation to OpenBUGS + commands <- c(paste("SamplesEmbed.beg :=", getOption("BRugsSamplesBeg")), + paste("SamplesEmbed.end :=", getOption("BRugsSamplesEnd")), + paste("SamplesEmbed.firstChain :=", getOption("BRugsSamplesFirstChain")), + paste("SamplesEmbed.lastChain :=", getOption("BRugsSamplesLastChain")), + paste("SamplesEmbed.thin :=", getOption("BRugsSamplesThin")), + paste("SamplesEmbed.SetVariable(", shQuote(node), ")", sep=""), + paste("BugsMappers.SetPrec(", getOption("BRugsPrec"), ")", sep="") + ) + options(options.old) + paste(commands, collapse="; ") +} Modified: branches/linux/BRugs/R/model.check.R =================================================================== --- branches/linux/BRugs/R/model.check.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/model.check.R 2010-08-07 19:37:04 UTC (rev 164) @@ -16,6 +16,7 @@ command <- gsub ("//", "/", command) } .CmdInterpreter(command) + .initGlobals() if(getOption("BRugsVerbose")) buffer() } Modified: branches/linux/BRugs/R/model.compile.R =================================================================== --- branches/linux/BRugs/R/model.compile.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/model.compile.R 2010-08-07 19:37:04 UTC (rev 164) @@ -10,6 +10,7 @@ .CmdInterpreter(command) samplesSetFirstChain(1) samplesSetLastChain(numChains) + options("BRugsNextChain" = 1) if(getOption("BRugsVerbose")) buffer() } Deleted: branches/linux/BRugs/R/model.getRN.R =================================================================== --- branches/linux/BRugs/R/model.getRN.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/model.getRN.R 2010-08-07 19:37:04 UTC (rev 164) @@ -1,7 +0,0 @@ -"modelGetRN" <- -function() -# Get the seed of random number generator -{ - command <- "BugsEmbed.preSet" - .Integer(command) -} Modified: branches/linux/BRugs/R/model.inits.R =================================================================== --- branches/linux/BRugs/R/model.inits.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/model.inits.R 2010-08-07 19:37:04 UTC (rev 164) @@ -31,6 +31,7 @@ cat("Initializing chain ", chainNum[i], ": ", sep="") buffer() } + options("BRugsNextChain" = chainNum[i] + 1) } invisible() } Modified: branches/linux/BRugs/R/model.names.R =================================================================== --- branches/linux/BRugs/R/model.names.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/model.names.R 2010-08-07 19:37:04 UTC (rev 164) @@ -6,15 +6,29 @@ number <- .Integer(command) name <- character(number) if(length(number)){ - for(i in 1:number){ - command <- paste("BugsRobjects.SetIndex(", i-1, ")", sep="") - .CmdInterpreter(command) - command <- "BugsRobjects.GetStringLength" - numchar <- .Integer(command) - command <- "BugsRobjects.GetVariable" - char <- paste(rep(" ", numchar), collapse="") - name[i] <- .C("CharArray", command, nchar(command), char, numchar, integer(1), PACKAGE="BRugs")[[3]] - } + cmds <- character(0) + cmdtype <- character() + for(i in 1:number){ + cmds <- c(cmds, paste("BugsRobjects.SetIndex(", i-1, ")", sep=""), + "BugsRobjects.GetStringLength") + cmdtype <- c(cmdtype, c("CmdInterpreter","Integer")) + } + res <- .OpenBUGS(cmds, cmdtype) + numchar <- unlist(res[seq(2, 2*number, by=2)]) + + cmds <- character(0) + cmdtype <- character() + args <- list() + for(i in 1:number){ + char <- paste(rep(" ", numchar[i]), collapse="") + cmds <- c(cmds, + paste("BugsRobjects.SetIndex(", i-1, ")", sep=""), + "BugsRobjects.GetVariable") + cmdtype <- c(cmdtype, c("CmdInterpreter","CharArray")) + args <- c(args, list(NA, char)) + } + res <- .OpenBUGS(cmds, cmdtype, args) + name <- unlist(res[seq(2, 2*number, by=2)]) } return(name) -} + } Modified: branches/linux/BRugs/R/model.precision.R =================================================================== --- branches/linux/BRugs/R/model.precision.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/model.precision.R 2010-08-07 19:37:04 UTC (rev 164) @@ -5,6 +5,7 @@ if(!is.numeric(prec)) stop("prec ", "must be numeric") prec <- as.integer(prec) - command <- paste("BugsMappers.SetPrec(", prec, ")") - invisible(.CmdInterpreter(command)) + options(BRugsPrec=prec) +# command <- paste("BugsMappers.SetPrec(", prec, ")") +# invisible(.CmdInterpreter(command)) } Modified: branches/linux/BRugs/R/model.setRN.R =================================================================== --- branches/linux/BRugs/R/model.setRN.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/model.setRN.R 2010-08-07 19:37:04 UTC (rev 164) @@ -6,9 +6,5 @@ stop("state must be an integer from 1 to 14") state <- as.integer(state) command <- paste("BugsEmbed.SetRNGuard; BugsEmbed.SetRNState(", state, ")" ) - res <- .CmdInterpreter(command)[[3]] - if(!res){ - if(getOption("BRugsVerbose")) - message("Random number generator state successfully set") - }else stop("Setting random number generator state returned with an error.") + invisible(.CmdInterpreter(command)) } Modified: branches/linux/BRugs/R/plot.bgr.R =================================================================== --- branches/linux/BRugs/R/plot.bgr.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/plot.bgr.R 2010-08-07 19:37:04 UTC (rev 164) @@ -1,13 +1,42 @@ "plotBgr" <- -function(node, plot = TRUE, main = NULL, xlab = "iteration", ylab = "bgr", - col = c("red", "blue", "green"), bins = 50, ...) -# Plot bgr diagnostic for single component of OpenBUGS name + function(node, plot = TRUE, main = NULL, xlab = "iteration", ylab = "bgr", + col = c("red", "blue", "green"), bins = 50, ...) + # Plot bgr diagnostic for single component of OpenBUGS name { sM <- samplesMonitors(node) if(length(sM) > 1 || sM != node) stop("node must be a scalar variable from the model, for arrays use samplesBgr") grid <- bgrGrid(node, bins = bins) - bgr <- sapply(grid, bgrPoint, node = node) + + ## Use a single API call instead of looping API calls over + ## iterations - more efficient with the Linux helper. + + ## find size of available sample at each grid point + res <- .OpenBUGS(cmds = c(.SamplesGlobalsCmd(node), + as.vector(rbind(paste("SamplesEmbed.end := ", grid, ";"), "SamplesEmbed.SampleSize;"))), + cmdtypes = c("CmdInterpreter", rep(c("CmdInterpreter","Integer"), bins)), + args=as.list(c(NA, rep(c(NA, NA), bins))) + ) + + args <- list(NA) + for (i in seq(length=bins)){ + args[[2*i]] <- NA + args[[2*i + 1]] <- double(res[[2*i + 1]]) + } + + ## get available sample at each grid point + res <- .OpenBUGS(cmds = + c(.SamplesGlobalsCmd(node), + as.vector(rbind(paste("SamplesEmbed.end := ", grid, ";"), "SamplesEmbed.SampleValues;"))), + cmdtypes = c("CmdInterpreter", rep(c("CmdInterpreter","RealArray"), bins)), + args=args) + + ## remove junk elements of list, leaving a list of samples for each grid point + res[c(1, 2*seq(length=bins))] <- NULL + + ## calculate between, within and ratio statistics for each grid point + bgr <- rbind(grid, sapply(res, bgrPoint)) + yRange <- range(bgr[4,]) yRange <- c(0, max(c(1.2, yRange[2]))) nRange <- range(bgr[2,]) @@ -21,7 +50,7 @@ bgr[3,] <- bgr[3,] / max if(plot){ plot(grid, bgr[4,], ylim = yRange, type = "l", - main = if(is.null(main)) node else main, xlab = xlab, ylab = ylab, col = col[1], ...) + main = if(is.null(main)) node else main, xlab = xlab, ylab = ylab, col = col[1], ...) lines(grid, bgr[2,], col = col[2], ...) lines(grid, bgr[3,], col = col[3], ...) } @@ -30,4 +59,5 @@ bgr$Iteration <- as.integer(bgr$Iteration) if(plot) invisible(bgr) else return(bgr) + } Modified: branches/linux/BRugs/R/samples.coda.R =================================================================== --- branches/linux/BRugs/R/samples.coda.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.coda.R 2010-08-07 19:37:04 UTC (rev 164) @@ -29,9 +29,8 @@ samplesSetLastChain(lastChain) thin <- max(c(thin, 1)) samplesSetThin(thin) - command <- paste("SamplesEmbed.SetVariable(", sQuote(node), - ");SamplesEmbed.StatsGuard;", "SamplesEmbed.CODA(", - sQuote(stem), ")") + command <- paste(.SamplesGlobalsCmd(node), ";SamplesEmbed.StatsGuard;", + "SamplesEmbed.CODA(", sQuote(stem), ")") .CmdInterpreter(command) buffer() } Modified: branches/linux/BRugs/R/samples.correl.R =================================================================== --- branches/linux/BRugs/R/samples.correl.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.correl.R 2010-08-07 19:37:04 UTC (rev 164) @@ -22,10 +22,16 @@ samplesSetLastChain(lastChain) thin <- max(c(thin, 1)) samplesSetThin(thin) - - command <- paste("CorrelEmbed.SetVariable0(", sQuote(node0), - ");CorrelEmbed.SetVariable1(", sQuote(node1), - ");CorrelEmbed.Guard", ";CorrelEmbed.PrintMatrix") + + command <- paste("CorrelEmbed.beg :=", getOption("BRugsSamplesBeg"), + "; CorrelEmbed.end :=", getOption("BRugsSamplesEnd"), + "; CorrelEmbed.firstChain :=", getOption("BRugsSamplesFirstChain"), + "; CorrelEmbed.lastChain :=", getOption("BRugsSamplesLastChain"), + "; CorrelEmbed.thin :=", getOption("BRugsSamplesThin"), + "; CorrelEmbed.SetVariable0(", sQuote(node0), + ");CorrelEmbed.SetVariable1(", sQuote(node1), + ");CorrelEmbed.Guard", ";CorrelEmbed.PrintMatrix" + ) .CmdInterpreter(command) buffer <- file.path(tempdir(), "buffer.txt") rlb <- readLines(buffer) Modified: branches/linux/BRugs/R/samples.get.beg.R =================================================================== --- branches/linux/BRugs/R/samples.get.beg.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.get.beg.R 2010-08-07 19:37:04 UTC (rev 164) @@ -1,7 +1,6 @@ "samplesGetBeg" <- function() -# Get the beg field +# Beginning iteration from which to compute sample statistics { - command <- "SamplesEmbed.beg" - .Integer(command) + getOption("BRugsSamplesBeg") } Modified: branches/linux/BRugs/R/samples.get.end.R =================================================================== --- branches/linux/BRugs/R/samples.get.end.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.get.end.R 2010-08-07 19:37:04 UTC (rev 164) @@ -1,7 +1,6 @@ "samplesGetEnd" <- function() -# Get the end field +# End iteration from which to compute sample statistics { - command <- "SamplesEmbed.end" - .Integer(command) + getOption("BRugsSamplesEnd") } Modified: branches/linux/BRugs/R/samples.get.firstChain.R =================================================================== --- branches/linux/BRugs/R/samples.get.firstChain.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.get.firstChain.R 2010-08-07 19:37:04 UTC (rev 164) @@ -1,7 +1,6 @@ "samplesGetFirstChain" <- function() -# Get the firstChain field +# First chain from which to compute sample statistics { - command <- "SamplesEmbed.firstChain" - .Integer(command) + getOption("BRugsSamplesFirstChain") } Modified: branches/linux/BRugs/R/samples.get.lastChain.R =================================================================== --- branches/linux/BRugs/R/samples.get.lastChain.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.get.lastChain.R 2010-08-07 19:37:04 UTC (rev 164) @@ -1,7 +1,6 @@ "samplesGetLastChain" <- function() -# Get the lastChain field +# Last chain from which to compute sample statistics { - command <- "SamplesEmbed.lastChain" - .Integer(command) + getOption("BRugsSamplesLastChain") } Modified: branches/linux/BRugs/R/samples.get.thin.R =================================================================== --- branches/linux/BRugs/R/samples.get.thin.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.get.thin.R 2010-08-07 19:37:04 UTC (rev 164) @@ -1,7 +1,6 @@ "samplesGetThin" <- function() -# Get the thin field +# Thinning interval to apply to sample statistics { - command <- "SamplesEmbed.thin" - .Integer(command) + getOption("BRugsSamplesThin") } Modified: branches/linux/BRugs/R/samples.monitors.R =================================================================== --- branches/linux/BRugs/R/samples.monitors.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.monitors.R 2010-08-07 19:37:04 UTC (rev 164) @@ -4,7 +4,7 @@ { if (is.R()){ command <- paste("SamplesEmbed.SetVariable(", sQuote(node), - ");SamplesEmbed.StatsGuard;SamplesEmbed.Labels") + ");SamplesEmbed.StatsGuard;SamplesEmbed.Labels",sep="") .CmdInterpreter(command) buffer <- file.path(tempdir(), "buffer.txt") rlb <- readLines(buffer) @@ -23,7 +23,7 @@ } else { sampsMonsSingle <- function(node){ command <- paste("SamplesEmbed.SetVariable(", sQuote(node), - ");SamplesEmbed.StatsGuard;SamplesEmbed.Labels") + ");SamplesEmbed.StatsGuard;SamplesEmbed.Labels",sep="") .CmdInterpreter(command) buffer <- file.path(tempdir(), "buffer.txt") rlb <- readLines(buffer) Modified: branches/linux/BRugs/R/samples.sample.R =================================================================== --- branches/linux/BRugs/R/samples.sample.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.sample.R 2010-08-07 19:37:04 UTC (rev 164) @@ -9,16 +9,14 @@ sM <- samplesMonitors(node)[1] if(sM == "model must be initialized before monitors used") stop("model must be initialized / updated / monitored before samplesSample is used") - - command <- "BugsRobjects.SetVariable" - .C("CharArray", command, nchar(command), node, nchar(node), integer(1), PACKAGE="BRugs") - command <- "BugsRobjects.GetSize" - nodeSize <- .Integer(command) - if(nodeSize > 1) + nodeSize <- .OpenBUGS(c("BugsRobjects.SetVariable", "BugsRobjects.GetSize"), + c("CharArray","Integer"), + list(node,NA))[[2]] + if(nodeSize > 1) stop("Only scalar nodes such as ", node, "[1] are allowed.") - sampleSize <- samplesSize(node) - command <- "SamplesEmbed.SampleValues" - .C("RealArray", command, nchar(command), - double(sampleSize), sampleSize, integer(1), PACKAGE="BRugs")[[3]] + sample <- .OpenBUGS(c(.SamplesGlobalsCmd(node), "SamplesEmbed.SampleValues"), + c("CmdInterpreter","RealArray"), + list(node,double(sampleSize)))[[2]] + sample } Modified: branches/linux/BRugs/R/samples.set.beg.R =================================================================== --- branches/linux/BRugs/R/samples.set.beg.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.set.beg.R 2010-08-07 19:37:04 UTC (rev 164) @@ -5,6 +5,5 @@ if(!is.numeric(begIt)) stop("begIt ", "must be numeric") begIt <- as.integer(begIt) - command <- paste("SamplesEmbed.beg :=", begIt) - invisible(.CmdInterpreter(command)) + options("BRugsSamplesBeg" = begIt) } Modified: branches/linux/BRugs/R/samples.set.end.R =================================================================== --- branches/linux/BRugs/R/samples.set.end.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.set.end.R 2010-08-07 19:37:04 UTC (rev 164) @@ -5,6 +5,5 @@ if(!is.numeric(endIt)) stop("endIt ", "must be numeric") endIt <- as.integer(endIt) - command <- paste("SamplesEmbed.end :=", endIt) - invisible(.CmdInterpreter(command)) + options("BRugsSamplesEnd" = endIt) } Modified: branches/linux/BRugs/R/samples.set.firstChain.R =================================================================== --- branches/linux/BRugs/R/samples.set.firstChain.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.set.firstChain.R 2010-08-07 19:37:04 UTC (rev 164) @@ -7,6 +7,5 @@ first <- as.integer(first) if(!(first %in% 1:getNumChains())) stop("it is required to have 1 <= first <= nchains") - command <- paste("SamplesEmbed.firstChain :=", as.integer(first)) - invisible(.CmdInterpreter(command)) + options("BRugsSamplesFirstChain" = first) } Modified: branches/linux/BRugs/R/samples.set.lastChain.R =================================================================== --- branches/linux/BRugs/R/samples.set.lastChain.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.set.lastChain.R 2010-08-07 19:37:04 UTC (rev 164) @@ -7,6 +7,5 @@ last <- as.integer(last) if(!(last %in% 1:getNumChains())) stop("it is required to have 1 <= last <= nchains") - command <- paste("SamplesEmbed.lastChain :=", last) - invisible(.CmdInterpreter(command)) + options("BRugsSamplesLastChain" = last) } Modified: branches/linux/BRugs/R/samples.set.thin.R =================================================================== --- branches/linux/BRugs/R/samples.set.thin.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.set.thin.R 2010-08-07 19:37:04 UTC (rev 164) @@ -4,6 +4,5 @@ { if(!is.numeric(thin)) stop("thin ", "must be numeric") - command <- paste("SamplesEmbed.thin :=", as.integer(thin)) - invisible(.CmdInterpreter(command)) + options("BRugsSamplesThin" = thin) } Modified: branches/linux/BRugs/R/samples.size.R =================================================================== --- branches/linux/BRugs/R/samples.size.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.size.R 2010-08-07 19:37:04 UTC (rev 164) @@ -9,8 +9,7 @@ if (any(grep("^model has probably not yet been updated", sM))) return(0) if(length(sM) > 1 || sM != node) stop("node must be a scalar variable from the model") - command <- paste("SamplesEmbed.SetVariable(", shQuote(node), ")") - .CmdInterpreter(command) - command <- "SamplesEmbed.SampleSize" - .Integer(command) + size <- .OpenBUGS(c(.SamplesGlobalsCmd(node), "SamplesEmbed.SampleSize"), + c("CmdInterpreter","Integer"))[[2]] + size } Modified: branches/linux/BRugs/R/samples.stats.R =================================================================== --- branches/linux/BRugs/R/samples.stats.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/samples.stats.R 2010-08-07 19:37:04 UTC (rev 164) @@ -22,7 +22,6 @@ samplesSetLastChain(lastChain) thin <- max(c(thin, 1)) samplesSetThin(thin) - nodeName <- sQuote(node) if (is.R()){ result <- data.frame(mean=NULL, sd=NULL, MC_error = NULL, val2.5pc=NULL, @@ -33,9 +32,8 @@ start = numeric(), sample=numeric()) } - for(i in seq(along=nodeName)){ - command <- paste("SamplesEmbed.SetVariable(", nodeName[i], - ");SamplesEmbed.StatsGuard;SamplesEmbed.Stats") + for(i in seq(along=node)){ + command <- paste(.SamplesGlobalsCmd(node), "SamplesEmbed.StatsGuard;SamplesEmbed.Stats") .CmdInterpreter(command) buffer <- file.path(tempdir(), "buffer.txt") rlb <- readLines(buffer) @@ -44,9 +42,9 @@ result <- rbind(result, read.table(buffer)) else{ if(length(grep("val97.5pc", rlb))) - message("Variable ", nodeName[i], " has probably not been updated") + message("Variable ", node[i], " has probably not been updated") else - message("Variable ", nodeName[i], ": ", rlb) + message("Variable ", node[i], ": ", rlb) } } return(result) Modified: branches/linux/BRugs/R/set.values.R =================================================================== --- branches/linux/BRugs/R/set.values.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/set.values.R 2010-08-07 19:37:04 UTC (rev 164) @@ -8,19 +8,16 @@ # if(any(DoNotSetNA)) # warning("Some NA values formerly had a non-NA value -- left unchanged") # values[DoNotSetNA] <- cv[DoNotSetNA] - if (dimensions(nodeLabel) == 0) - stop("Only allowed for vector, not scalar nodes") - command <- "BugsRobjects.SetVariable" - .C("CharArray", command, nchar(command), nodeLabel, nchar(nodeLabel), integer(1), PACKAGE="BRugs") - command <- "BugsRobjects.GetSize" - nodeSize <- .Integer(command) + nodeSize <- .OpenBUGS(c("BugsRobjects.SetVariable", "BugsRobjects.GetSize"), + c("CharArray","Integer"), + c(nodeLabel,NA))[[2]] if(nodeSize == -1) stop(nodeLabel, " is not a node in BUGS model") - if(length(values) != nodeSize) - stop("length(values) does not correspond to the node size") - command <- "BugsRobjects.SetValues" - res <- .C("RealArray", command, nchar(command), as.double(values), as.integer(nodeSize), - integer(1), NAOK = TRUE, PACKAGE="BRugs") - handleRes(res[[5]]) + numChains <- getNumChains() + if(length(values) != nodeSize*numChains) + stop("length(values) does not correspond to the node size and number of chains") + .OpenBUGS(c("BugsRobjects.SetVariable", "BugsRobjects.SetValues"), + c("CharArray","RealArray"), + list(nodeLabel,as.double(values)))[[2]] invisible() } Modified: branches/linux/BRugs/R/zzz.R =================================================================== --- branches/linux/BRugs/R/zzz.R 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/R/zzz.R 2010-08-07 19:37:04 UTC (rev 164) @@ -1,27 +1,62 @@ if (is.R()){ - ".onLoad" <- function(lib, pkg){ + .initGlobals <- function(){ + options("BRugsSamplesBeg" = 1) + options("BRugsSamplesEnd" = 10000000) + options("BRugsSamplesFirstChain" = 1) + options("BRugsSamplesLastChain" = 1) + options("BRugsSamplesThin" = 1) + options("BRugsSamplesVariable" = "*") + options("BRugsNextChain" = 1) # index of chain which needs to be initialized next + options("BRugsPrec" = 4) + } + + .onLoad <- function(...) { + switch(Sys.info()["sysname"], + "Linux" = .onLoad.Linux(...), + "Windows" = .onLoad.Windows(...), + stop("Only Linux and Windows are supported")) + if(is.null(getOption("BRugsVerbose"))) + options("BRugsVerbose" = TRUE) + .initGlobals() + } + + ".onLoad.Windows" <- function(lib, pkg){ ## sets path / file variables and initializes subsystems root <- file.path(system.file("OpenBUGS", package=pkg)) - ## we do have a NAMESPACE now: library.dynam("BRugs", pkg, lib) + library.dynam("BRugs", pkg, lib) len <- nchar(root) tempDir <- gsub("\\\\", "/", tempdir()) .C("SetWorkingDir", as.character(root), len, PACKAGE="BRugs") .C("SetTempDir", as.character(tempDir), nchar(tempDir), PACKAGE="BRugs") command <- "BugsMappers.SetDest(2)" .CmdInterpreter(command) - if(is.null(getOption("BRugsVerbose"))) - options("BRugsVerbose" = TRUE) } + + ".onLoad.Linux" <- function(lib, pkg){ + ## TODO any need for these to be user specifiable? + options("BRugsTmpdir" = gsub("\\\\", "/", tempdir())) + options("BRugsExtFile" = paste(basename(tempfile()), ".bug", sep="")) + } ".onAttach" <- function(lib, pkg){ - message("Welcome to BRugs running on OpenBUGS version 3.1.0") + message("Welcome to BRugs running on OpenBUGS version 3.1.2") } - - ".onUnload" <- function(libpath){ + + .onUnload <- function(...) { + switch(Sys.info()["sysname"], + "Linux" = .onUnload.Linux(...), + "Windows" = .onUnload.Windows(...), + stop("Only Linux and Windows are supported")) + } + + ".onUnload.Windows" <- function(libpath){ library.dynam.unload("BRugs", libpath) } + ".onUnload.Linux" <- function(libpath){ + } + ## Overwriting new (from R-2.6.0) sQuote (for typing human readable text) in R within the BRugs Namespace! ## we cannot use sQuote that uses fancy quotes! sQuote <- function(x) paste("'", x, "'", sep="") Deleted: branches/linux/BRugs/configure =================================================================== --- branches/linux/BRugs/configure 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/configure 2010-08-07 19:37:04 UTC (rev 164) @@ -1,3 +0,0 @@ -echo "Package 'BRugs' currently only works under Windows.\nIt is supposed to work under Linux in future releases." -exit 1 - Deleted: branches/linux/BRugs/configure.win =================================================================== Modified: branches/linux/BRugs/man/BRugs.Rd =================================================================== --- branches/linux/BRugs/man/BRugs.Rd 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/man/BRugs.Rd 2010-08-07 19:37:04 UTC (rev 164) @@ -1,43 +1,43 @@ -\name{BRugs} +\name{BRugs} \alias{BRugs} \alias{help.BRugs} -\title{Introduction to BRugs} -\description{This manual describes how to use the BRugs software} +\title{Introduction to BRugs} +\description{This manual describes how to use the BRugs software} \usage{ help.BRugs(browser = getOption("browser")) } \arguments{ -\item{browser}{the name of the program to be used as hypertext browser. +\item{browser}{the name of the program to be used as hypertext browser. It should be in the PATH, or a full path specified.} } \details{ - BRugs is a collection of R functions that - allow users to analyze graphical models using MCMC techniques. Most of the R functions in BRugs provide a - interface to the BRugs dynamic link library (shared object file). The BRugs dynamic link library is able to make - use of many of the WinBUGS components, in particular those components concerned with graphical models and MCMC - simulation. BRugs lacks the GUI interface of WinBUGS but is able to use R to create graphical displays of the - MCMC simulation. BRugs uses the same model specification language as WinBUGS and the same format for data and - initial values. However BRugs always uses plain text files for input inplace of WinBUGS compound documents. The - BRugs functions can be split into two groups: those associated with setting up and simulating the graphical model - and those associated with making statistical inference. In general the R functions in BRugs correspond to the - command buttons and text entry fields in the menus of WinBUGS. Each WinBUGS text entry field splits into two + BRugs is a collection of R functions that + allow users to analyze graphical models using MCMC techniques. Most of the R functions in BRugs provide a + interface to the BRugs dynamic link library (shared object file). The BRugs dynamic link library is able to make + use of many of the WinBUGS components, in particular those components concerned with graphical models and MCMC + simulation. BRugs lacks the GUI interface of WinBUGS but is able to use R to create graphical displays of the + MCMC simulation. BRugs uses the same model specification language as WinBUGS and the same format for data and + initial values. However BRugs always uses plain text files for input inplace of WinBUGS compound documents. The + BRugs functions can be split into two groups: those associated with setting up and simulating the graphical model + and those associated with making statistical inference. In general the R functions in BRugs correspond to the + command buttons and text entry fields in the menus of WinBUGS. Each WinBUGS text entry field splits into two R functions, one to set the quantity and the other to get the value of the quantity. - - Andrew Gelman suggests to use the function \code{bugs} in the \pkg{R2WinBUGS} package + + Andrew Gelman suggests to use the function \code{bugs} in the \pkg{R2WinBUGS} package with argument \code{program="openbugs"} as a wrapper. } \section{Permission and Disclaimer}{ - BRugs is released under the GNU GENERAL PUBLIC LICENSE. + BRugs is released under the GNU GENERAL PUBLIC LICENSE. For details see \url{http://mathstat.helsinki.fi/openbugs/} or type \code{help.BRugs()}. - More informally, potential users are reminded to be extremely careful if using this program for serious - statistical analysis. We have tested the program on quite a wide set of examples, but be particularly careful - with types of model that are currently not featured. If there is a problem, BRugs might just crash, which is not - very good, but it might well carry on and produce answers that are wrong, which is even worse. Please let us know + More informally, potential users are reminded to be extremely careful if using this program for serious + statistical analysis. We have tested the program on quite a wide set of examples, but be particularly careful + with types of model that are currently not featured. If there is a problem, BRugs might just crash, which is not + very good, but it might well carry on and produce answers that are wrong, which is even worse. Please let us know of any successes or failures. -} +} %\references{} -\seealso{\code{\link{help.WinBUGS}} (which currently is called from \code{help.BRugs}) and the meta function \code{\link{BRugsFit}}} +\seealso{\code{\link{help.WinBUGS}} (which currently is called from \code{help.BRugs}) and the meta function \code{\link{BRugsFit}}} \examples{ ### Step by step example: ### library(BRugs) # loading BRugs @@ -47,10 +47,10 @@ setwd(system.file("OpenBUGS", "Examples", package="BRugs")) ## some usual steps (like clicking in WinBUGS): -modelCheck("ratsmodel.txt") # check model file -modelData("ratsdata.txt") # read data file +modelCheck("Ratsmodel.txt") # check model file +modelData("Ratsdata.txt") # read data file modelCompile(numChains=2) # compile model with 2 chains -modelInits(rep("ratsinits.txt", 2)) # read init data file +modelInits(rep("Ratsinits.txt", 2)) # read init data file modelUpdate(1000) # burn in samplesSet(c("alpha0", "alpha")) # alpha0 and alpha should be monitored modelUpdate(1000) # 1000 more iterations .... @@ -64,11 +64,11 @@ samplesAutoC("alpha[1:6]", 1) # plot autocorrelations of 1st chain ## switch back to the previous working directory: -setwd(oldwd) +setwd(oldwd) \dontrun{ # Getting more (online-)help: if (is.R()) - help.BRugs() + help.BRugs() } } \keyword{interface} Modified: branches/linux/BRugs/man/BRugsFit.Rd =================================================================== --- branches/linux/BRugs/man/BRugsFit.Rd 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/man/BRugsFit.Rd 2010-08-07 19:37:04 UTC (rev 164) @@ -52,8 +52,8 @@ Andrew Gelman proposes some \code{print} and \code{plot} methods that can be accessed by the \code{openbugs} (and \code{bugs}) and \code{as.bugs.array} functions in the CRAN package \pkg{R2WinBUGS}.} \examples{ -BRugsFit(data = "ratsdata.txt", inits = "ratsinits.txt", - para = c("alpha", "beta"), modelFile = "ratsmodel.txt", +BRugsFit(data = "Ratsdata.txt", inits = "Ratsinits.txt", + para = c("alpha", "beta"), modelFile = "Ratsmodel.txt", numChains = 1, working.directory = system.file("OpenBUGS", "Examples", package = "BRugs")) Modified: branches/linux/BRugs/man/bgr.point.Rd =================================================================== --- branches/linux/BRugs/man/bgr.point.Rd 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/man/bgr.point.Rd 2010-08-07 19:37:04 UTC (rev 164) @@ -7,12 +7,13 @@ } \usage{ bgrGrid(node, bins = 50) -bgrPoint(node, iteration) +bgrPoint(sample) } \arguments{ \item{node}{Character vector of length 1, name of a variable in the model.} \item{bins}{Blocksize} - \item{iteration}{Calculated by \code{bgrGrid}} + \item{sample}{Monitored sample from multiple chains to calculate the + convergence statistic for.} } \note{Intended for internal use only.} \seealso{\code{\link{samplesBgr}}, \code{\link{BRugs}}, \code{\link{help.WinBUGS}}} Modified: branches/linux/BRugs/man/model.RN.Rd =================================================================== --- branches/linux/BRugs/man/model.RN.Rd 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/man/model.RN.Rd 2010-08-07 19:37:04 UTC (rev 164) @@ -1,11 +1,9 @@ \name{modelRN} \alias{modelSetRN} -\alias{modelGetRN} \title{State of Random Number Generator} -\description{These functions set/return the starting state of the random number generator.} +\description{Set the starting state of the random number generator.} \usage{ modelSetRN(state) -modelGetRN() } \arguments{ \item{state}{An integer from 1 to 14. The internal state of the OpenBUGS random number generator can be set to one of 14 predefined states. Each predefined state is \eqn{10^12}{10^12} draws apart to avoid overlap in random number sequences.} Modified: branches/linux/BRugs/man/set.values.Rd =================================================================== --- branches/linux/BRugs/man/set.values.Rd 2010-08-07 18:10:35 UTC (rev 163) +++ branches/linux/BRugs/man/set.values.Rd 2010-08-07 19:37:04 UTC (rev 164) @@ -2,12 +2,13 @@ \alias{setValues} \title{Setting current values} \description{This function sets the current values of a variable for future - iterations. Only supported for vector, not scalar nodes.} + iterations. Only stochastic nodes can be set using this facility, and + logical nodes are then updated if necessary. } \usage{ setValues(nodeLabel, values) } \arguments{ - \item{nodeLabel}{Character vector of length 1, name of a vector node in the model.} + \item{nodeLabel}{Character vector of length 1, name of a node in the model.} \item{values}{The values to be set, generated, e.g., by \code{\link{infoNodeValues}}.} } \details{ Added: branches/linux/BRugs/src/BugsHelper.c =================================================================== --- branches/linux/BRugs/src/BugsHelper.c (rev 0) +++ branches/linux/BRugs/src/BugsHelper.c 2010-08-07 19:37:04 UTC (rev 164) @@ -0,0 +1,300 @@ +/* BugsHelper - Perform one or more OpenBUGS API commands as specified +in the command line arguments. + +ARGUMENTS (not named) + + argv[1]: Full path to temporary directory containing the buffer file + for messages from the main API commands, and any input and output + corresponding to the commands. + + argv[2]: Full path to temporary directory containing the buffer file + for messages from the Internalize and Externalize commands. We do not + want these to overwrite the main buffer. + + argv[3]: Name of the file used to store the externalized model + state. This will be saved in the directory specified in argv[1]. + + The remaining arguments argv[4], argv[5], ... specify any number of + calls to OpenBUGS API functions. These are given in the order: + + cmd, cmdtype, cmd, cmdtype, ... + + where "cmd" is an OpenBUGS API command, and "cmdtype" is an integer + specifying the API function being called. Currently allowed values of + "cmdtype" are + + 0 : if "cmd" is a call to the "CmdInterpreter" API function + 1 : if "cmd" is a call to the "Integer" API function + 2 : if "cmd" is a call to the "CharArray" API function + 3 : if "cmd" is a call to the "RealArray" API function + + +INPUT AND OUTPUT + + Some OpenBUGS commands require input or produce output. The input and + output for the Nth command given in the call to BugsHelper are stored + in files called inputN.txt and outputN.txt, and are saved in the + directory specified in argv[1]. + + +EXAMPLE + + The following command checks a BUGS model file stored in the file + /path/to/Examples/Ratsmodel.txt and then loads a data file from + /path/to/Examples/Ratsdata.txt. Temporary files are stored in + subdirectories of /tmp. + + "BugsEmbed.SetFilePath('/scratch/chris/lib/R/BRugs/OpenBUGS/Examples/Ratsdata.txt');BugsEmbed.LoadDataGuard;BugsEmbed.LoadData" 0 + + /path/to/BugsHelper "/tmp/RtmpaRQois" "/tmp/RtmpaRQois_trash" "file327b23c6.bug" "BugsEmbed.SetFilePath('/path/to/Examples/Ratsmodel.txt');BugsEmbed.ParseGuard;BugsEmbed.Parse" 0 "BugsEmbed.SetFilePath('/path/to/Examples/Ratsdata.txt');BugsEmbed.LoadDataGuard;BugsEmbed.LoadData" 0 + + +AUTHOR + + Chris Jackson <chr...@mr...> + + */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <sys/stat.h> + +#define NODEBUG + +/* OpenBUGS API functions from libOpenBUGS.so */ +int errno; +extern void CLI (); +extern void BugsCmd(char **command, int *len); +extern void CharArray (char **procedure, int *len, char **x, int *lenX, int *res); +extern void CmdInterpreter (char **command, int *len, int *res); +extern void Guard (char **procedure, int *len, int *x, int *res); +extern void Integer (char **procedure, int *len, int *x, int *res); +extern void IntegerArray (char **procedure, int *len, int *x, int *lenX, int *res); +extern void Real (char **procedure, int *len, double *x, double *y, int *res); +extern void RealArray (char **procedure, int *len, double *x, int *lenX, int *res); +extern void SetWorkingDir (char **path, int *len); +extern void SetTempDir(char **path, int *len); +extern void UseBufferFile (); +extern void UseConsole (); + +void read_input_real(char *tmpdir, double **out, int *len, int cmdno) { + char *fname; + struct stat buf; + FILE *ifp; + double tmp; + fname = (char *) malloc(strlen(tmpdir) + 16); + sprintf(fname, "%s/input%d.txt", tmpdir, cmdno); + if (stat(fname, &buf) != -1) { + *len = 0; + ifp = fopen(fname, "r"); + while (fscanf(ifp, "%lf", &tmp) == 1) + ++*len; + *out = (double *) malloc(sizeof(double)*(*len)); +#ifdef DEBUG + printf("Reading %d values from %s\n", *len, fname); +#endif + fseek(ifp, 0, SEEK_SET); /* move to start of file */ + *len = 0; + while (fscanf(ifp, "%lf", &((*out)[*len])) == 1){ + ++*len; + } + fclose(ifp); + } + free(fname); +} + +int file_size() { +} + +void read_input_char(char *tmpdir, char **out, int *len, int cmdno) { + char *fname; + struct stat buf; + FILE *ifp; + fname = (char *) malloc(strlen(tmpdir) + 16); + sprintf(fname, "%s/input%d.txt", tmpdir, cmdno); + if (stat(fname, &buf) != -1) { + *len = buf.st_size; + *out = (char *) malloc(*len + 1); + ifp = fopen(fname, "r"); +#ifdef DEBUG + printf("Reading %d characters from %s\n", *len, fname); +#endif + *len = 0; + while(((*out)[*len] = getc(ifp)) != EOF) { + ++*len; + } + (*out)[*len] = '\0'; + fclose(ifp); + } + free(fname); +} + +void write_output_int(char *tmpdir, int out, int cmdno) { + char *fname; + FILE *ofp; + fname = (char *) malloc(strlen(tmpdir) + 16); + sprintf(fname, "%s/output%d.txt", tmpdir, cmdno); + ofp = fopen(fname, "w"); +#ifdef DEBUG + printf("Writing integer %d to %s\n", out, fname); +#endif + fprintf(ofp, "%d", out); + fclose(ofp); + free(fname); +} + +void write_output_real(char *tmpdir, double *out, int len, int cmdno) { + char *fname; + FILE *ofp; + int i; + fname = (char *) malloc(strlen(tmpdir) + 16); + sprintf(fname, "%s/output%d.txt", tmpdir, cmdno); + ofp = fopen(fname, "w"); +#ifdef DEBUG + printf("Writing %d reals to %s\n", len, fname); +#endif + for (i=0; i<len; ++i) + fprintf(ofp, "%lf ", out[i]); // TODO is precision acceptable? + fclose(ofp); + free(fname); +} + +void write_output_char(char *tmpdir, char *out, int cmdno) { + char *fname; + FILE *ofp; + fname = (char *) malloc(strlen(tmpdir) + 16); + sprintf(fname, "%s/output%d.txt", tmpdir, cmdno); +#ifdef DEBUG + printf("Writing string %s to %s\n", out, fname); +#endif + ofp = fopen(fname, "w"); + fprintf(ofp, "%s", out); + fclose(ofp); + free(fname); +} + +int do_TempDir(char *dir) { + int length; + length = strlen(dir); + SetTempDir(&dir, &length); +} + +int do_Cmd(char *cmd) { + int length, res; + length = strlen(cmd); +#ifdef DEBUG + printf("%s: %d\n", cmd, strlen(cmd)); +#endif + CmdInterpreter(&cmd, &length, &res); + return res; +} + +int do_Integer(char *cmd, char *tmpdir, int cmdno) { + int length, out, res; + // doesn't need input -- assume only used for reading integers + length = strlen(cmd); +#ifdef DEBUG + printf("%s: %d\n", cmd, strlen(cmd)); +#endif + Integer(&cmd, &length, &out, &res); + write_output_int(tmpdir, out, cmdno); + return res; +} + +int do_CharArray(char *cmd, char *tmpdir, int cmdno) { + int length, outlength, res; + char *out; + int i; + length = strlen(cmd); + read_input_char(tmpdir, &out, &outlength, cmdno); +#ifdef DEBUG + printf("%s: args=%s, arglength=%d\n", cmd, out, outlength); +#endif + CharArray(&cmd, &length, &out, &outlength, &res); + write_output_char(tmpdir, out, cmdn... [truncated message content] |
From: <chr...@us...> - 2010-08-07 18:10:41
|
Revision: 163 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=163&view=rev Author: chris-jackson Date: 2010-08-07 18:10:35 +0000 (Sat, 07 Aug 2010) Log Message: ----------- Added Paths: ----------- branches/linux/BRugs/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-08-07 18:08:33
|
Revision: 162 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=162&view=rev Author: chris-jackson Date: 2010-08-07 18:08:27 +0000 (Sat, 07 Aug 2010) Log Message: ----------- Added Paths: ----------- branches/linux/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <snt...@us...> - 2010-08-06 14:07:47
|
Revision: 161 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=161&view=rev Author: snthomas99 Date: 2010-08-06 14:07:38 +0000 (Fri, 06 Aug 2010) Log Message: ----------- updates to documentation and some bug fixes Modified Paths: -------------- trunk/R2OpenBUGS/DESCRIPTION trunk/R2OpenBUGS/NAMESPACE trunk/R2OpenBUGS/R/bugs.R trunk/R2OpenBUGS/R/bugs.script.R trunk/R2OpenBUGS/man/R2WinBUGS-package.Rd trunk/R2OpenBUGS/man/bugs.Rd trunk/R2OpenBUGS/man/bugs.run.Rd trunk/R2OpenBUGS/man/bugs.script.Rd Removed Paths: ------------- trunk/R2OpenBUGS/R/openbugs.R trunk/R2OpenBUGS/man/openbugs.Rd Modified: trunk/R2OpenBUGS/DESCRIPTION =================================================================== --- trunk/R2OpenBUGS/DESCRIPTION 2010-07-25 02:45:16 UTC (rev 160) +++ trunk/R2OpenBUGS/DESCRIPTION 2010-08-06 14:07:38 UTC (rev 161) @@ -1,21 +1,19 @@ -Package: R2WinBUGS -Title: Running WinBUGS and OpenBUGS from R / S-PLUS -Date: 2010-03-18 -Version: 2.1-17 -Author: originally written by Andrew Gelman <ge...@st...>; +Package: R2OpenBUGS +Title: Running OpenBUGS from R / S-PLUS +Date: 2010-08-5 +Version: 1.0-0 +Author: originally written as R2WinBUGS by Andrew Gelman <ge...@st...>; changes and packaged by Sibylle Sturtz <st...@st...> and Uwe Ligges <li...@st...>. With considerable contributions by Gregor Gorjanc <gre...@bf...> and Jouni Kerman <ke...@st...>. - Ported to S-PLUS by Insightful Corp. + Ported to S-PLUS by Insightful Corp. Adapted to R2OpenBUGS from R2WinBUGS by Neal Thomas. Description: Using this package, it is possible 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. -Depends: R (>= 2.5.0), coda (>= 0.11-0) -Suggests: BRugs (>= 0.3-2) -SystemRequirements: WinBUGS 1.4 + in R / S-PLUS. +Depends: R (>= 2.9.2), coda (>= 0.11-0) +SystemRequirements: OpenBUGS >=3.1 URL: http://www.stat.columbia.edu/~gelman/bugsR/ Maintainer: Uwe Ligges <li...@st...> License: GPL-2 Modified: trunk/R2OpenBUGS/NAMESPACE =================================================================== --- trunk/R2OpenBUGS/NAMESPACE 2010-07-25 02:45:16 UTC (rev 160) +++ trunk/R2OpenBUGS/NAMESPACE 2010-08-06 14:07:38 UTC (rev 161) @@ -9,7 +9,6 @@ read.bugs, bugs.log, monitor, - openbugs, as.bugs.array, write.model) Modified: trunk/R2OpenBUGS/R/bugs.R =================================================================== --- trunk/R2OpenBUGS/R/bugs.R 2010-07-25 02:45:16 UTC (rev 160) +++ trunk/R2OpenBUGS/R/bugs.R 2010-08-06 14:07:38 UTC (rev 161) @@ -17,15 +17,16 @@ if(.Platform$OS.type != "windows" & useWINE==FALSE){ if(debug)stop("The debug option is not available with linux/unix") if(save.history)("History plots (save.history) is not available with linux/unix") - }else{ - if(!file.exists(OpenBUGS.pgm)) - stop("OpenBUGS executable was not found" ) } if (missing(OpenBUGS.pgm) && !is.null(bugs.pgm <- getOption("R2OpenBUGS.pgm"))) { # requested by Jouni Kerman OpenBUGS.pgm<- bugs.pgm } + + if((.Platform$OS.type == "windows" | useWINE) & !file.exists(OpenBUGS.pgm)) + stop("OpenBUGS executable was not found" ) + ## Is OpenBUGS.pgm defined in Windows (where second character is : ## i.e. C:\Program...) or Unix style path? if(useWINE && (substr(OpenBUGS.pgm, 2, 2) == ":")) { Modified: trunk/R2OpenBUGS/R/bugs.script.R =================================================================== --- trunk/R2OpenBUGS/R/bugs.script.R 2010-07-25 02:45:16 UTC (rev 160) +++ trunk/R2OpenBUGS/R/bugs.script.R 2010-08-06 14:07:38 UTC (rev 161) @@ -36,7 +36,7 @@ function(x, useWINE, newWINE, WINEPATH) {native2win(x, useWINE=useWINE, newWINE=newWINE, WINEPATH=WINEPATH)}) - initlist <- paste("modelInits(", 1:n.chains, ", '", inits, "')\n", sep="") + initlist <- paste("modelInits(", "'", inits, "',",1:n.chains,")\n", sep="") savelist <- paste("samplesSet(", parameters.to.save, ")\n", sep="") summarylist <- paste("summarySet(", parameters.to.save, ")\n", sep="") Deleted: trunk/R2OpenBUGS/R/openbugs.R =================================================================== --- trunk/R2OpenBUGS/R/openbugs.R 2010-07-25 02:45:16 UTC (rev 160) +++ trunk/R2OpenBUGS/R/openbugs.R 2010-08-06 14:07:38 UTC (rev 161) @@ -1,114 +0,0 @@ -openbugs <- function(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) -{ - if(!is.R()) - stop("OpenBUGS is not yet available in S-PLUS") - if(!require("BRugs")) - stop("BRugs is required") - - ## switching from bugs() to BRugsFit() notation - modelFile <- model.file - numChains <- n.chains - nBurnin <- n.burnin - nIter <- n.iter - n.burnin - nThin <- n.thin - if(DIC) parameters.to.save <- c(parameters.to.save, "deviance") - parametersToSave <- parameters.to.save - - ## Move to working drirectory or temporary directory when NULL - if(is.null(working.directory)) { - working.directory <- tempdir() - inTempDir <- TRUE - } - savedWD <- getwd() - setwd(working.directory) - on.exit(setwd(savedWD)) - - if(inTempDir && basename(model.file) == model.file) - try(file.copy(file.path(savedWD, model.file), model.file, overwrite = TRUE)) - if(!file.exists(modelFile)) { - stop(modelFile, " does not exist") - } - if(file.info(modelFile)$isdir) { - stop(modelFile, " is a directory, but a file is required") - } - ## kludge to add carriage-returns (line-feeds?) to the model file - if(!length(grep("\r\n", readChar(modelFile, 10^3)))) { - message("Carriage returns added to model file ", modelFile) - model <- readLines(modelFile) - try(writeLines(model, modelFile)) - } - BRugs::modelCheck(modelFile) - if(!(is.vector(data) && is.character(data) && all(file.exists(data)))) { - data <- BRugs::bugsData(data, digits = digits) - } - if(inTempDir && all(basename(data) == data)) - try(file.copy(file.path(savedWD, data), data, overwrite = TRUE)) - BRugs::modelData(data) - BRugs::modelCompile(numChains) - if(!is.null(seed)) BRugs::modelSetRN(seed) - if(missing(inits) || is.null(inits)) { - BRugs::modelGenInits() - } else { - if(is.list(inits) || is.function(inits) || (is.character(inits) && - !any(file.exists(inits)))) { - inits <- BRugs::bugsInits(inits = inits, numChains = numChains, - digits = digits) - } - if(inTempDir && all(basename(inits) == inits)) - try(file.copy(file.path(savedWD, inits), inits, overwrite = TRUE)) - BRugs::modelInits(inits) - BRugs::modelGenInits() - } - BRugs::samplesSetThin(nThin) - ## set the adaptive phases - -## We do no longer have any Registry.txt file availabe, -## hence not resetting the adaptive phase any more. -## People should move to BRugs directly. -# adaptivelines <- scan(system.file("OpenBUGS", "Bugs", "Rsrc", -# "Registry.txt", package="BRugs"), -# what="character", quiet = TRUE) -# factories <- sub(".adaptivePhase", "", -# adaptivelines[grep("adaptivePhase",adaptivelines)]) -# sapply(factories, BRugs::modelSetAP, max(0, nBurnin-1)) - if(getOption("BRugsVerbose")){ - cat("Sampling has been started ...\n") - flush.console() - } - BRugs::modelUpdate(nBurnin, overRelax = over.relax) - ## BRugs::samplesSetThin(nThin) - if(DIC) { - BRugs::dicSet() - on.exit(BRugs::dicClear(), add = TRUE) - } - BRugs::samplesSet(parametersToSave) - BRugs::modelUpdate(nIter, overRelax = over.relax) - params <- sort.name(BRugs::samplesMonitors("*"), parametersToSave) - samples <- sapply(params, BRugs::samplesSample) - n.saved.per.chain <- nrow(samples)/numChains - samples.array <- array(samples, c(n.saved.per.chain, numChains, ncol(samples))) - dimnames(samples.array)[[3]] <- dimnames(samples)[[2]] - if(DIC) { - DICOutput <- BRugs::dicStats() - } else { - DICOutput <- NULL - } - bugs.output <- as.bugs.array(sims.array=samples.array, - model.file=modelFile, program="OpenBUGS", - DIC=DIC, DICOutput=DICOutput, - n.iter=n.iter, n.burnin=n.burnin, n.thin=n.thin) - bugs.output -} - -## sorter called by openbugs() to save the parameters in the specified order -sort.name <- function(a, b){ - ## sort the scalar parameter names in the vector "a" according to the - ## ordering of their stems in the shorter vector "b" - bracket.pos <- regexpr("\\[", a) - a.stem <- substr(a, 1, ifelse(bracket.pos>0, bracket.pos-1, nchar(a))) - a[order(match(a.stem, b))] -} Modified: trunk/R2OpenBUGS/man/R2WinBUGS-package.Rd =================================================================== --- trunk/R2OpenBUGS/man/R2WinBUGS-package.Rd 2010-07-25 02:45:16 UTC (rev 160) +++ trunk/R2OpenBUGS/man/R2WinBUGS-package.Rd 2010-08-06 14:07:38 UTC (rev 161) @@ -1,37 +1,35 @@ -\name{R2WinBUGS-package} -\alias{R2WinBUGS-package} -\alias{R2WinBUGS} +\name{R2OpenBUGS-package} +\alias{R2OpenBUGS-package} +\alias{R2OpenBUGS} \docType{package} -\title{Running WinBUGS and OpenBUGS from R / S-PLUS} +\title{Running OpenBUGS from R / S-PLUS} \description{ -\pkg{R2WinBUGS} package provides possiblity to call a \pkg{BUGS} model, +\pkg{R2OpenBUGS} Call a \pkg{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 -\pkg{OpenBUGS} functionality and the windows emulation functionality is -not yet available. The main command is \code{\link{bugs}}. +simulations in arrays for easy access in \R / S-PLUS. The main command is \code{\link{bugs}}. } \details{ -The following are sources of information on \pkg{R2WinBUGS} package: +The following are sources of information on \pkg{R2OpenBUGS} package: \tabular{ll}{ - DESCRIPTION file\tab \code{library(help="R2WinBUGS")}\cr + DESCRIPTION file\tab \code{library(help="R2OpenBUGS")}\cr \tab \cr - This file\tab \code{package?R2WinBUGS}\cr + This file\tab \code{package?R2OpenBUGS}\cr \tab \cr - Vignette\tab \code{vignette("R2WinBUGS")}\cr + Vignette\tab \code{vignette("R2OpenBUGS")}\cr \tab \cr Some help files\tab \code{\link{bugs}}\cr \tab \code{\link{write.model}}\cr \tab \code{\link{print.bugs}}\cr \tab \code{\link{plot.bugs}}\cr \tab \cr - News\tab \code{file.show(system.file("NEWS", package="R2WinBUGS"))}\cr + News\tab \code{file.show(system.file("NEWS", package="R2OpenBUGS"))}\cr } } Modified: trunk/R2OpenBUGS/man/bugs.Rd =================================================================== --- trunk/R2OpenBUGS/man/bugs.Rd 2010-07-25 02:45:16 UTC (rev 160) +++ trunk/R2OpenBUGS/man/bugs.Rd 2010-08-06 14:07:38 UTC (rev 161) @@ -3,21 +3,22 @@ \title{Run WinBUGS and OpenBUGS from R or S-PLUS} \description{The \code{bugs} function takes data and starting values as - input. It automatically writes a \pkg{WinBUGS} script, calls the model, and + input. It automatically writes a \pkg{OpenBUGS} script, calls the model, and saves the simulations for easy access in \R or S-PLUS.} \usage{ -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, +bugs(data, inits, parameters.to.save, n.iter, model.file="model.bug", + n.chains=3, n.burnin=floor(n.iter / 2), n.thin=1, 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) + OpenBUGS.pgm=ifelse(.Platform$OS.type == "windows" | useWINE==TRUE, + paste("C:/Program Files/OpenBUGS/OpenBUGS", + version,"/OpenBUGS.exe",sep=""),"OpenBUGS"), + version='311', + 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{ @@ -38,7 +39,7 @@ parameters to save which should be monitored} \item{model.file}{file containing the model written in \pkg{WinBUGS} code. The extension can be either \file{.bug} or \file{.txt}. - If the extension is \file{.bug} and \code{program=="WinBUGS"}, + If the extension is \file{.bug} and \code{program=="OpenBUGS"}, a copy of the file with extension \file{.txt} will be created in the \code{bugs()} call and removed afterwards. Note that similarly named \file{.txt} files will be overwritten. @@ -50,41 +51,37 @@ \item{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{n.thin}{thinning rate. Must be a positive integer. Set - \code{n.thin} > 1 to save memory and computation time if - \code{n.iter} is large. Default is \code{max(1, floor(n.chains * - (n.iter-n.burnin) / 1000))} which will only thin if there are at - least 2000 simulations.} - \item{n.sims}{The approximate number of simulations to keep after thinning.} - \item{bin}{number of iterations between saving of results - (i.e. the coda files are saved after each \code{bin} iterations); - default is to save only at the end.} - \item{debug}{if \code{FALSE} (default), \pkg{WinBUGS} is closed automatically - when the script has finished running, otherwise \pkg{WinBUGS} remains open - for further investigation} + \item{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 \ocde{n.burnin} or + \oode{n.iter}. Setting \ocde{n.thin}=2, doubles the number of iterations OpenBUGS + performs, but does not change \ocde{n.iter} or \ocde{n.burnin}. Thinning implemented + in this manner is not captured in summaries created by packages such as \pkg{coda}.} + \item{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{DIC}{logical; if \code{TRUE} (default), compute deviance, pD, - and DIC. This is done in \pkg{WinBUGS} directly using the rule \code{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{digits}{number of significant digits used for \pkg{WinBUGS} input, see + \item{digits}{number of significant digits used for \pkg{OpenBUGS} input, see \code{\link{formatC}}} \item{codaPkg}{logical; if \code{FALSE} (default) a \code{bugs} object is returned, if \code{TRUE} file names of \pkg{WinBUGS} output are returned for easy access by the \pkg{coda} package through function - \code{\link{read.bugs}} (not used if \code{program="OpenBUGS"}). + \code{\link{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{\link[coda]{as.mcmc.list}} - (for which a method is provided by R2WinBUGS).} - \item{bugs.directory}{directory that contains the \pkg{WinBUGS} executable. - If the global option \code{R2WinBUGS.bugs.directory} is not \code{NULL}, + (for which a method is provided by R2OpenBUGS).} + \item{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 the global option \code{R2OpenBUGS.bugs.directory} is not \code{NULL}, it will be used as the default.} - \item{program}{the program to use, either - \code{winbugs}/\code{WinBUGS} or \code{openbugs}/\code{OpenBUGS}, - the latter makes use of function \code{\link{openbugs}} and requires - the CRAN package \pkg{BRugs}. The \code{openbugs}/\code{OpenBUGS} - choice is not available in S-PLUS.} + \item{version}{The version of OpenBUGS to use. \ocde{version} is ignored + with linux execution or if \code{OpenBUGS.pgm} is specified.} \item{working.directory}{sets working directory during execution of - this function; \pkg{WinBUGS}' in- and output will be stored in this + this function; \pkg{OpenBUGS}' in- and output will be stored in this directory; if \code{NULL}, a temporary working directory via \code{\link{tempdir}} is used.} \item{clearWD}{logical; indicating whether the files \file{data.txt}, @@ -92,23 +89,21 @@ and \file{coda[1:nchains].txt} should be removed after \pkg{WinBUGS} has finished. If set to \code{TRUE}, this argument is only respected if \code{codaPkg=FALSE}.} - \item{useWINE}{logical; attempt to use the Wine emulator to run - \pkg{WinBUGS}, defaults to \code{FALSE} on Windows, and \code{TRUE} - otherwise. Not available in S-PLUS.} - \item{WINE}{character, path to \file{wine} binary file, it is + \pkg{OpenBUGS}. Default is \code{FALSE}.} + \item{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{newWINE}{Use new versions of Wine that have \file{winepath} utility} - \item{WINEPATH}{character, path to \file{winepath} binary file, it is + \item{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{bugs.seed}{random seed for \pkg{WinBUGS} (default is no seed)} + \item{bugs.seed}{Random seed for \pkg{OpenBUGS}}. \item{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{save.history}{If \code{TRUE} (the default), trace plots are generated at the end.} - \item{over.relax}{If \code{TRUE}, over-relaxed form of MCMC is used if available from WinBUGS.} + \item{over.relax}{If \code{TRUE}, over-relaxed form of MCMC is used if available from OpenBUGS.} } \details{ @@ -119,36 +114,34 @@ \item Go into \R / S-PLUS. \item Prepare the inputs for the \code{bugs} function and run it (see Example section). - \item A \pkg{WinBUGS} window will pop up and \R / S-PLUS will freeze - up. The model will now run in \pkg{WinBUGS}. It might take awhile. You - will see things happening in the Log window within \pkg{WinBUGS}. When - \pkg{WinBUGS} is done, its window will close and \R / S-PLUS will work + \item An \pkg{OpenBUGS} window will pop up and \R / S-PLUS 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 / S-PLUS will work again. \item If an error message appears, re-run with \code{debug=TRUE}. } BUGS version support: \itemize{ - \item{\pkg{WinBUGS} 1.4.*}{default} - \item{\pkg{OpenBUGS} 2.*}{via argument \code{program="OpenBUGS"}} + \item{\pkg{OpenBUGS} >3.1}{} } Operation system support: \itemize{ \item{\pkg{MS Windows}}{no problem} - \item{\pkg{Linux}, \pkg{Mac OS X} and \pkg{Unix} in - general}{possible with Wine emulation via \code{useWINE=TRUE}, but - only for \pkg{WinBUGS} 1.4.*} + \item{\pkg{Linux, intel processors}}{GUI display and graphics not available.} + \item{\pkg{Mac OS X} and \pkg{Unix} in + general}{possible with Wine emulation via \code{useWINE=TRUE}} } 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{bugs.directory} can be given in - Windows path style (e.g. \dQuote{c:/Program Files/WinBUGS14/}) or + Windows path style (e.g. \dQuote{c:/Program Files/OpenBUGS/}) or native (Unix) style (e.g. \dQuote{/path/to/wine/folder/dosdevices/c:/Program - Files/WinBUGS14}). This is done to achieve greatest portability with - default argument value for \code{bugs.directory}. + Files/OpenBUGS}). }. } @@ -193,7 +186,7 @@ \item{indexes.short}{indexes of \code{root.short}} \item{last.values}{list of simulations from the most recent iteration; they can be used as starting points if you wish to run - \pkg{WinBUGS} for further iterations} + \pkg{OpenBUGS} for further iterations} \item{pD}{an estimate of the effective number of parameters, for calculations see the section \dQuote{Arguments}.} \item{DIC}{\code{mean(deviance) + pD}} @@ -211,14 +204,14 @@ \author{Andrew Gelman, \email{ge...@st...}, \url{http:/www.stat.columbia.edu/~gelman/bugsR/}; modifications and packaged by Sibylle Sturtz, \email{st...@st...}, - and Uwe Ligges.} + Uwe Ligges. and Neal Thomas} \seealso{\code{\link{print.bugs}}, \code{\link{plot.bugs}}, as well as \pkg{coda} and \pkg{BRugs} packages} \examples{ # An example model file is given in: -model.file <- system.file(package="R2WinBUGS", "model", "schools.txt") +model.file <- system.file(package="R2OpenBUGS", "model", "schools.txt") # Let's take a look: file.show(model.file) @@ -249,8 +242,7 @@ ## 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/") + n.chains=3, n.iter=5000) print(schools.sim) plot(schools.sim) } Modified: trunk/R2OpenBUGS/man/bugs.run.Rd =================================================================== --- trunk/R2OpenBUGS/man/bugs.run.Rd 2010-07-25 02:45:16 UTC (rev 160) +++ trunk/R2OpenBUGS/man/bugs.run.Rd 2010-08-06 14:07:38 UTC (rev 161) @@ -1,20 +1,19 @@ \name{bugs.run} \alias{bugs.run} -\title{Calling WinBUGS} +\title{Calling OpenBUGS} -\description{Updates the lengths of the adaptive phases in the - \pkg{WinBUGS} registry (using \code{\link{bugs.update.settings}}), - calls \pkg{WinBUGS} and runs it with \file{script.txt} - intended for +\description{ + Calls \pkg{OpenBUGS} and runs it with \file{script.txt} - intended for internal use} \usage{ -bugs.run(n.burnin, bugs.directory, - useWINE=.Platform$OS.type != "windows", WINE=NULL, +bugs.run(n.burnin, OpenBUGS.pgm, + useWINE=FALSE, WINE=NULL, newWINE=TRUE, WINEPATH=NULL) } \arguments{ \item{n.burnin}{length of burn in} - \item{bugs.directory}{directory that contains the \pkg{WinBUGS} executable} + \item{OpenBUGS.pgm}{Full path to the \pkg{OpenBUGS} executable or shell script} \item{useWINE}{as in \code{\link{bugs}} meta function} \item{WINE}{as in \code{\link{bugs}} meta function} \item{newWINE}{as in \code{\link{bugs}} meta function} @@ -22,7 +21,7 @@ } \value{Nothing, but has side effects as documented in - \code{\link{bugs.update.settings}} and calls \pkg{WinBUGS}.} + \code{\link{bugs.update.settings}} and calls \pkg{OpenBUGS}.} \seealso{The main function to be called by the user is \code{\link{bugs}}.} \keyword{internal} Modified: trunk/R2OpenBUGS/man/bugs.script.Rd =================================================================== --- trunk/R2OpenBUGS/man/bugs.script.Rd 2010-07-25 02:45:16 UTC (rev 160) +++ trunk/R2OpenBUGS/man/bugs.script.Rd 2010-08-06 14:07:38 UTC (rev 161) @@ -1,42 +1,46 @@ \name{bugs.script} \alias{bugs.script} -\title{Writes script for running WinBUGS} +\title{Writes script for running OpenBUGS} -\description{Write file \file{script.txt} for \pkg{WinBUGS} to read - +\description{Write file \file{script.txt} for \pkg{OpenBUGS} to read - intended for internal use} \usage{ -bugs.script(parameters.to.save, n.chains, n.iter, n.burnin, n.thin, - model.file, debug=FALSE, is.inits, bin, DIC=FALSE, - useWINE=.Platform$OS.type != "windows", newWINE=TRUE, WINEPATH=NULL, - bugs.seed=NULL, summary.only=FALSE, save.history=TRUE, - bugs.data.file, bugs.inits.files, over.relax = FALSE) +bugs.script(parameters.to.save, n.chains, n.iter, n.burnin, + n.thin, model.file, debug=FALSE, is.inits, + DIC=FALSE, useWINE=FALSE, + newWINE=TRUE, WINEPATH=NULL, bugs.seed=NULL, summary.only=FALSE, + save.history=(.Platform$OS.type = "windows" | useWINE=TRUE), + bugs.data.file, bugs.inits.files, + over.relax = FALSE) } \arguments{ \item{parameters.to.save}{parameters that should be monitored} \item{n.chains}{number of Markov chains} \item{n.iter}{number of total iterations (including burn in)} \item{n.burnin}{length of burn in} - \item{n.thin}{size of thinning parameter} - \item{model.file}{file containing the model written in \pkg{WinBUGS} code} - \item{debug}{if \code{FALSE}, \pkg{WinBUGS} is closed automatically, - otherwise \pkg{WinBUGS} remains open for further investigation} + \item{n.thin}{thinning parameter} + \item{model.file}{file containing the model written in \pkg{OpenBUGS} code} + \item{debug}{if \code{FALSE}, \pkg{OpenBUGS} is closed automatically, + otherwise \pkg{OpenBUGS} remains open for further investigation. With + \code{debug} = \code{TRUE}, no modelQuit() command is added to the + end of the script, which can cause an infinite loop with linux + execution.} \item{is.inits}{logical; whether initial values are given by the user - (\code{TRUE}) or have to be generated by \pkg{WinBUGS}} - \item{bin}{number of iterations between saving of results} + (\code{TRUE}) or have to be generated by \pkg{OpenBUGS}} \item{DIC}{logical; if \code{TRUE}, compute deviance, pD, and DIC - automatically in \pkg{WinBUGS}} + automatically in \pkg{OpenBUGS}} \item{useWINE}{as in \code{\link{bugs}} meta function} \item{newWINE}{as in \code{\link{bugs}} meta function} \item{WINEPATH}{as in \code{\link{bugs}} meta function} - \item{bugs.seed}{random seed for \pkg{WinBUGS} (default is no seed)} + \item{bugs.seed}{random seed for \pkg{OpenBUGS} (default is no seed specified)} \item{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{save.history}{If \code{TRUE} (the default), trace plots are generated at the end.} \item{bugs.data.file}{character name of the data file} \item{bugs.inits.files}{character vector of names of the inits files} - \item{over.relax}{If \code{TRUE}, over-relaxed form of MCMC is used if available from WinBUGS.} + \item{over.relax}{If \code{TRUE}, over-relaxed form of MCMC is used if available from OpenBUGS.} } \value{Nothing, but as a side effect, the script file \file{script.txt} Deleted: trunk/R2OpenBUGS/man/openbugs.Rd =================================================================== --- trunk/R2OpenBUGS/man/openbugs.Rd 2010-07-25 02:45:16 UTC (rev 160) +++ trunk/R2OpenBUGS/man/openbugs.Rd 2010-08-06 14:07:38 UTC (rev 161) @@ -1,118 +0,0 @@ -\name{openbugs} -\alias{openbugs} -\title{Wrapper to run OpenBUGS} -\description{The \code{openbugs} function takes data and starting values - as input. It automatically calls the package \pkg{BRugs} and runs - something similar to \code{\link[BRugs]{BRugsFit}}. Not available in - S-PLUS.} - -\usage{ -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) -} - -\arguments{ - \item{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{\link{bugs.data}}.} - \item{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} are missing or \code{inits = NULL}, - initial values are generated by \pkg{OpenBUGS}.} - \item{parameters.to.save}{character vector of the names of the - parameters to save which should be monitored} - \item{model.file}{file containing the model written in \pkg{OpenBUGS} code. - The extension can be either \file{.bug} or \file{.txt}. If - \file{.bug}, a copy of the file with extension \file{.txt} will be - created in the \code{bugs()} call and removed afterwards. Note that - similarly named \file{.txt} files will be overwritten.} - \item{n.chains}{number of Markov chains (default: 3)} - \item{n.iter}{number of total iterations per chain (including burn in; - default: 2000)} - \item{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{n.thin}{thinning rate. Must be a positive integer. Set - \code{n.thin} > 1 to save memory and computation time if - \code{n.iter} is large. Default is \code{max(1, floor(n.chains * - (n.iter-n.burnin) / 1000))} which will only thin if there are at - least 2000 simulations.} - \item{n.sims}{The approximate number of simulations to keep after thinning.} - \item{DIC}{logical; if \code{TRUE} (default), compute deviance, pD, and - DIC. This is done in \pkg{BRugs} directly.} - \item{digits}{number of significant digits used for \pkg{OpenBUGS} input, - see \code{\link{formatC}}} - \item{bugs.directory}{directory that contains the \pkg{OpenBUGS} executable - - currently unused} - \item{working.directory}{sets working directory during execution of - this function; \pkg{WinBUGS} in- and output will be stored in this - directory; if \code{NULL}, a temporary working directory via - \code{\link{tempdir}} is used.} - \item{over.relax}{If \code{TRUE}, over-relaxed form of MCMC is used if available from OpenBUGS.} - \item{seed}{random seed (default is no seed)} -} - -\value{A \code{\link{bugs}} object.} - -\author{Andrew Gelman, \email{ge...@st...}, - \url{http:/www.stat.columbia.edu/~gelman/bugsR/}; modifications and - packaged by Sibylle Sturtz, \email{st...@st...}, - and Uwe Ligges. -} - -\note{By default, BRugs (and hence \code{openbugs()}) is quite verbose. - This can be controlled for the whole BRugs package by the option \sQuote{BRugsVerbose} (see \code{\link{options}}) - which is set to \code{TRUE} by default. -} - -\seealso{\code{\link{bugs}} and the \pkg{BRugs} package} - -\examples{ -# 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") - -\dontrun{ -## 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) -} -} -\keyword{interface} -\keyword{models} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <snt...@us...> - 2010-07-25 02:45:22
|
Revision: 160 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=160&view=rev Author: snthomas99 Date: 2010-07-25 02:45:16 +0000 (Sun, 25 Jul 2010) Log Message: ----------- Updating R2WinBUGS to a new version for OpenBUGS using OpenBUGS scripting rather than BRugs Modified Paths: -------------- trunk/R2OpenBUGS/R/bugs.R trunk/R2OpenBUGS/R/bugs.data.R trunk/R2OpenBUGS/R/bugs.log.R trunk/R2OpenBUGS/R/bugs.run.R trunk/R2OpenBUGS/R/bugs.script.R trunk/R2OpenBUGS/R/bugs.sims.R trunk/R2OpenBUGS/R/write.model.R Added Paths: ----------- trunk/R2OpenBUGS/ Modified: trunk/R2OpenBUGS/R/bugs.R =================================================================== --- trunk/R2WinBUGS/R/bugs.R 2010-05-17 21:16:20 UTC (rev 159) +++ trunk/R2OpenBUGS/R/bugs.R 2010-07-25 02:45:16 UTC (rev 160) @@ -1,34 +1,47 @@ "bugs" <- -function(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, +function(data, inits, parameters.to.save, n.iter, model.file="model.bug", + n.chains=3, n.burnin=floor(n.iter / 2), n.thin=1, debug=FALSE, DIC=TRUE, digits=5, codaPkg=FALSE, - bugs.directory="c:/Program Files/WinBUGS14/", - program=c("WinBUGS", "OpenBUGS", "winbugs", "openbugs"), + OpenBUGS.pgm=ifelse(.Platform$OS.type == "windows" | useWINE==TRUE, + paste("C:/Program Files/OpenBUGS/OpenBUGS", + version,"/OpenBUGS.exe",sep=""),"OpenBUGS"), + version='311', 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) + 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) { + + ### check options for unix/linux + if(.Platform$OS.type != "windows" & useWINE==FALSE){ + if(debug)stop("The debug option is not available with linux/unix") + if(save.history)("History plots (save.history) is not available with linux/unix") + }else{ + if(!file.exists(OpenBUGS.pgm)) + stop("OpenBUGS executable was not found" ) + } + + if (missing(OpenBUGS.pgm) && + !is.null(bugs.pgm <- getOption("R2OpenBUGS.pgm"))) { # requested by Jouni Kerman + OpenBUGS.pgm<- bugs.pgm + } + ## Is OpenBUGS.pgm defined in Windows (where second character is : + ## i.e. C:\Program...) or Unix style path? + if(useWINE && (substr(OpenBUGS.pgm, 2, 2) == ":")) { + OpenBUGS.pgm<- win2native(OpenBUGS.pgm, newWINE=newWINE, WINEPATH=WINEPATH) + } + + + if(! bugs.seed %in% c(1:14))stop("OpenBUGS seed must be integer in 1-14") + if(!is.null(working.directory)) { working.directory <- path.expand(working.directory) savedWD <- getwd() setwd(working.directory) on.exit(setwd(savedWD)) } - program <- match.arg(program) - if (missing(bugs.directory) && - !is.null(bugs.dir <- getOption("R2WinBUGS.bugs.directory"))) { # requested by Jouni Kerman - bugs.directory <- bugs.dir - } - if(program %in% c("openbugs", "OpenBUGS", "OpenBugs")) { - if(!is.R()) stop("OpenBUGS is not yet available in S-PLUS") - ## If OpenBUGS, we only call openbugs() and exit... - return(openbugs(data, inits, parameters.to.save, model.file, - n.chains, n.iter, n.burnin, n.thin, n.sims, DIC=DIC, - bugs.directory, working.directory, digits, over.relax = over.relax, seed=bugs.seed)) - } + ## Checking number of inits, which is NOT saved here: if(!missing(inits) && !is.function(inits) && !is.null(inits) && (length(inits) != n.chains)) stop("Number of initialized chains (length(inits)) != n.chains") @@ -36,7 +49,7 @@ ## Wine if(useWINE) { if(!is.R()) - stop("Non-Windows platforms not yet supported in R2WinBUGS for S-PLUS") + stop("Non-Windows platforms not yet supported in R2OpenBUGS for S-PLUS") ## Attempt to find wine and winepath if(is.null(WINE)) WINE <- findUnixBinary(x="wine") if(is.null(WINEPATH)) WINEPATH <- findUnixBinary(x="winepath") @@ -121,27 +134,30 @@ } bugs.script(parameters.to.save, n.chains, n.iter, n.burnin, n.thin, new.model.file, debug=debug, is.inits=!is.null(inits), - bin=bin, DIC=DIC, useWINE=useWINE, newWINE=newWINE, + DIC=DIC, useWINE=useWINE, newWINE=newWINE, WINEPATH=WINEPATH, bugs.seed=bugs.seed, summary.only=summary.only, save.history=save.history, bugs.data.file = bugs.data.file, bugs.inits.files = bugs.inits.files, over.relax = over.relax) - bugs.run(n.burnin, bugs.directory, WINE=WINE, useWINE=useWINE, + bugs.run(n.burnin, OpenBUGS.pgm, WINE=WINE, useWINE=useWINE, newWINE=newWINE, WINEPATH=WINEPATH) if(codaPkg) - return(file.path(getwd(), paste("coda", 1:n.chains, ".txt", sep=""))) + return(file.path(getwd(), paste("CODAchain", 1:n.chains, ".txt", sep=""))) if (summary.only) { return(bugs.log("log.txt")) } sims <- c(bugs.sims(parameters.to.save, n.chains, n.iter, n.burnin, n.thin, DIC), - model.file=model.file, program=program) + model.file=model.file) if(clearWD) { - file.remove(c(bugs.data.file, "log.odc", "log.txt", "codaIndex.txt", + file.remove(c(bugs.data.file, "log.odc", "log.txt", "CODAIndex.txt", bugs.inits.files, "script.txt", - paste("coda", 1:n.chains, ".txt", sep=""))) + paste("CODAchain", 1:n.chains, ".txt", sep=""))) } class(sims) <- "bugs" sims } + + + Modified: trunk/R2OpenBUGS/R/bugs.data.R =================================================================== --- trunk/R2WinBUGS/R/bugs.data.R 2010-05-17 21:16:20 UTC (rev 159) +++ trunk/R2OpenBUGS/R/bugs.data.R 2010-07-25 02:45:16 UTC (rev 160) @@ -37,21 +37,21 @@ "writeDatafileS4" <- # -# Writes to file "towhere" text defining a list containing "DATA" in a form compatable with WinBUGS. +# Writes to file "towhere" text defining a list containing "DATA" in a form compatable with OpenBUGS. # Required arguments: # DATA - either a data frame or else a list consisting of any combination of scalars, vectors, arrays or data frames (but not lists). # If a list, all list elements that are not data.frames must be named. Names of data.frames in DATA are ignored. # Optional arguments: -# towhere - file to receive output. Is clipboard by default, which is convenient for pasting into a WinBUTS ODC file. +# towhere - file to receive output. Is clipboard by default, which is convenient for pasting into a OpenBUGS ODC file. # fill - If numeric, number of columns for output. If FALSE, output will be on one line. If TRUE (default), number of # columns is given by .Options$width. # Value: # Text defining a list is output to file "towhere". # Details: -# The function performs considerable checking of DATA argument. Since WinBUGS requires numeric input, no factors or character vectors +# The function performs considerable checking of DATA argument. Since OpenBUGS requires numeric input, no factors or character vectors # are allowed. All data must be named, either as named elements of DATA (if it is a list) or else using the names given in data frames. # Data frames may contain matrices. -# Arrays of any dimension are rearranged to be in row-major order, as required by WinBUGS. Scientific notation is also handled properly. +# Arrays of any dimension are rearranged to be in row-major order, as required by OpenBUGS. Scientific notation is also handled properly. # In particular, the number will consist of a mantissa _containing a decimal point_ followed by "E", then either "+" or "-", and finally # a _two-digit_ number. S-Plus does not always provide a decimal point in the mantissa, uses "e" instead of "E", followed by # either a "+" or "-" and then _three_ digits. @@ -62,7 +62,7 @@ { formatDataS4 = # - # Prepared DATA for input to WinBUGS. + # Prepared DATA for input to OpenBUGS. function(DATA) { if(!is.list(DATA)) @@ -113,13 +113,13 @@ charind <- sapply(DATA, is.character) if(any(charind)) stop(paste( - "WinBUGS does not handle character data. One or more character variables were detected:", + "OpenBUGS does not handle character data. One or more character variables were detected:", paste(dlnames[charind], collapse = ", "))) # Checking for complex vectors.... complexind <- sapply(DATA, is.complex) if(any(complexind)) stop(paste( - "WinBUGS does not handle complex data. One or more complex variables were detected:", + "OpenBUGS does not handle complex data. One or more complex variables were detected:", paste(dlnames[complexind], collapse = ", "))) # Checking for values farther from zero than 1E+38 (which is limit of single precision).... toobigind <- sapply(DATA, function(x) @@ -130,7 +130,7 @@ ) if(any(toobigind)) stop(paste( - "WinBUGS works in single precision. The following variables contain data outside the range +/-1.0E+38: ", + "OpenBUGS works in single precision. The following variables contain data outside the range +/-1.0E+38: ", paste(dlnames[toobigind], collapse = ", "), ".\n", sep = "")) # Checking for values in range +/-1.0E-38 (which is limit of single precision).... @@ -169,7 +169,7 @@ collapse = ", "), ")", sep = "") if(any(toosmallind)) warning(paste( - "WinBUGS works in single precision. The following variables contained nonzero data", + "OpenBUGS works in single precision. The following variables contained nonzero data", "\ninside the range +/-1.0E-38 that were set to zero: ", paste(dlnames[toosmallind], collapse = ", "), ".\n", sep = "")) Modified: trunk/R2OpenBUGS/R/bugs.log.R =================================================================== --- trunk/R2WinBUGS/R/bugs.log.R 2010-05-17 21:16:20 UTC (rev 159) +++ trunk/R2OpenBUGS/R/bugs.log.R 2010-07-25 02:45:16 UTC (rev 160) @@ -1,6 +1,6 @@ bugs.log <- function (file) { - # Extracts the summary statistics from log.txt written by WinBUGS. + # Extracts the summary statistics from log.txt written by OpenBUGS. # Jouni Kerman 2007-01-30 # does essentially the same thing as bugs.log() but # - won't crash if DIC is not there Modified: trunk/R2OpenBUGS/R/bugs.run.R =================================================================== --- trunk/R2WinBUGS/R/bugs.run.R 2010-05-17 21:16:20 UTC (rev 159) +++ trunk/R2OpenBUGS/R/bugs.run.R 2010-07-25 02:45:16 UTC (rev 160) @@ -1,54 +1,47 @@ "bugs.run" <- - function(n.burnin, bugs.directory, - useWINE=.Platform$OS.type != "windows", WINE=NULL, + function(n.burnin, OpenBUGS.pgm, + useWINE=FALSE, WINE=NULL, newWINE=TRUE, WINEPATH=NULL) { if(useWINE && !is.R()) - stop("Non-Windows platforms not yet supported in R2WinBUGS for S-PLUS") + stop("Non-Windows platforms not yet supported in R2OpenBUGS for S-PLUS") - ## Is bugs.directory defined in Windows (where second character is : - ## i.e. C:\Program...) or Unix style path? - if(useWINE && (substr(bugs.directory, 2, 2) == ":")) { - bugs.directory <- win2native(bugs.directory, newWINE=newWINE, WINEPATH=WINEPATH) - } - ## Update the lengths of the adaptive phases in the Bugs updaters - try(bugs.update.settings(n.burnin, bugs.directory)) +# try(bugs.update.settings(n.burnin, bugs.directory)) +# +# ## Return the lengths of the adaptive phases to their original settings +# if(is.R()) { +# .fileCopy <- file.copy +# } else { +# .fileCopy <- splus.file.copy +# } +# on.exit(try(.fileCopy(file.path(bugs.directory, "System/Rsrc/Registry_Rsave.odc"), +# file.path(bugs.directory, "System/Rsrc/Registry.odc"), +# overwrite=TRUE))) - ## Return the lengths of the adaptive phases to their original settings - if(is.R()) { - .fileCopy <- file.copy - } else { - .fileCopy <- splus.file.copy - } - on.exit(try(.fileCopy(file.path(bugs.directory, "System/Rsrc/Registry_Rsave.odc"), - file.path(bugs.directory, "System/Rsrc/Registry.odc"), - overwrite=TRUE))) - ## Search Win*.exe (WinBUGS executable) within bugs.directory - dos.location <- file.path(bugs.directory, - grep("^Win[[:alnum:]]*[.]exe$", - list.files(bugs.directory), value=TRUE)[1]) - if(!file.exists(dos.location)) - stop(paste("WinBUGS executable does not exist in", bugs.directory)) - ## Call Bugs and have it run with script.txt - bugsCall <- paste("\"", dos.location, "\" /par \"", - native2win(file.path(getwd(), "script.txt"), - useWINE=useWINE, newWINE=newWINE, WINEPATH=WINEPATH), - "\"", sep="") - if(useWINE) bugsCall <- paste(WINE, bugsCall) + if(.Platform$OS.type == "windows" | useWINE==TRUE){ + bugsCall <- paste("\"", OpenBUGS.pgm, "\" /PAR \"", + native2win(file.path(getwd(), "script.txt"), + useWINE=useWINE, newWINE=newWINE, WINEPATH=WINEPATH), + "\" /", sep="") + if(useWINE) bugsCall <- paste(WINE, bugsCall) + }else{ + bugsCall<-paste(OpenBUGS.pgm,"<","script.txt",">",file.path(getwd(),"log.txt")) + } temp <- system(bugsCall) if(temp == -1) - stop("Error in bugs.run().\nCheck that WinBUGS is in the specified directory.") + stop("Error in bugs.run().") + ## !!!! need to check these conditions ## Stop and print an error message if Bugs did not run correctly if(is.R()) { - tmp <- scan("coda1.txt", character(), quiet=TRUE, sep="\n") + tmp <- scan("CODAchain1.txt", character(), quiet=TRUE, sep="\n") } else { - tmp <- scan("coda1.txt", character(), sep="\n") + tmp <- scan("CODAchain1.txt", character(), sep="\n") } - if(length(grep("BUGS did not run correctly", tmp)) > 0) - stop("Look at the log file and\ntry again with 'debug=TRUE' to figure out what went wrong within Bugs.") + tmp<-tmp[1:min(100,length(tmp))] + if(length(grep("OpenBUGS did not run correctly", tmp)) > 0) stop("Look at the log file and\ntry again with 'debug=TRUE' to figure out what went wrong within OpenBUGS.") } Modified: trunk/R2OpenBUGS/R/bugs.script.R =================================================================== --- trunk/R2WinBUGS/R/bugs.script.R 2010-05-17 21:16:20 UTC (rev 159) +++ trunk/R2OpenBUGS/R/bugs.script.R 2010-07-25 02:45:16 UTC (rev 160) @@ -1,14 +1,15 @@ "bugs.script" <- function(parameters.to.save, n.chains, n.iter, n.burnin, - n.thin, model.file, debug=FALSE, is.inits, bin, - DIC=FALSE, useWINE=.Platform$OS.type != "windows", + n.thin, model.file, debug=FALSE, is.inits, + DIC=FALSE, useWINE=FALSE, newWINE=TRUE, WINEPATH=NULL, bugs.seed=NULL, summary.only=FALSE, - save.history=TRUE, bugs.data.file, bugs.inits.files, + save.history=(.Platform$OS.type = "windows" | useWINE=TRUE), + bugs.data.file, bugs.inits.files, over.relax = FALSE) { ## Write file script.txt for Bugs - if((ceiling(n.iter/n.thin) - ceiling(n.burnin/n.thin)) < 2) - stop ("(n.iter-n.burnin)/n.thin must be at least 2") + if(n.iter - n.burnin < 2) + stop ("(n.iter-n.burnin) must be at least 2") working.directory <- getwd() script <- "script.txt" @@ -19,13 +20,10 @@ else file.path(working.directory, model.file) model <- native2win(model, useWINE=useWINE, newWINE=newWINE, WINEPATH=WINEPATH) - history <- file.path(working.directory, "history.odc") - history <- native2win(history, useWINE=useWINE, newWINE=newWINE, WINEPATH=WINEPATH) - data <- file.path(working.directory, bugs.data.file) data <- native2win(data, useWINE=useWINE, newWINE=newWINE, WINEPATH=WINEPATH) - coda <- file.path(working.directory, "coda") + coda <- file.path(working.directory, "/") coda <- native2win(coda, useWINE=useWINE, newWINE=newWINE, WINEPATH=WINEPATH) logFile <- file.path(working.directory, "log.odc") @@ -38,45 +36,43 @@ function(x, useWINE, newWINE, WINEPATH) {native2win(x, useWINE=useWINE, newWINE=newWINE, WINEPATH=WINEPATH)}) - initlist <- paste("inits (", 1:n.chains, ", '", inits, "')\n", sep="") + initlist <- paste("modelInits(", 1:n.chains, ", '", inits, "')\n", sep="") - savelist <- paste("set (", parameters.to.save, ")\n", sep="") - redo <- ceiling((n.iter-n.burnin)/(n.thin*bin)) + savelist <- paste("samplesSet(", parameters.to.save, ")\n", sep="") + summarylist <- paste("summarySet(", parameters.to.save, ")\n", sep="") bugs.seed.cmd <- "" if (!is.null(bugs.seed)) { - bugs.seed.cmd <- paste("set.seed(", bugs.seed, ")\n", sep="") + bugs.seed.cmd <- paste("modelSetRN(", bugs.seed, ")\n", sep="") } - thinUpdate <- paste("thin.updater (", n.thin, ")\n", - "update (", ceiling(n.burnin/n.thin), ")\n", sep="") + thinUpdate <- paste("modelUpdate(", n.burnin, ",", n.thin, ")\n", sep="") cat( - "display ('log')\n", - "check ('", model, "')\n", - "data ('", data, "')\n", + "modelDisplay('log')\n", + "modelCheck('", model, "')\n", + "modelData('", data, "')\n", + "modelCompile(", n.chains, ")\n", bugs.seed.cmd, - "compile (", n.chains, ")\n", if(is.inits) initlist, - "gen.inits()\n", + "modelGenInits()\n", if(over.relax) 'over.relax("yes")\n', thinUpdate, savelist, - if(DIC) "dic.set()\n", - rep(c("update (", formatC(ceiling(bin), format = "d"), ")\n", - #if (!summary.only) ## Hmm, if coda files are not written, we do not know if WinBUGS did not fail - c("coda (*, '", coda, "')\n")), - redo), - "stats (*)\n", - if(DIC) "dic.stats()\n", - if (save.history) c("history (*, '", history, "')\n"), - "save ('", logFile, "')\n", - "save ('", logFileTxt, "')\n", + summarylist, + if(DIC) "dicSet()\n", + "modelUpdate(", n.iter-n.burnin, ",", n.thin, ")\n", + "samplesCoda('*', '", coda, "')\n", + "summaryStats('*')\n", + if(DIC) "dicStats()\n", + if (save.history) "samplesHistory('*')\n", + if(.Platform$OS.type == "windows" | useWINE) c("modelSaveLog('", logFile, "')\n", + "modelSaveLog('", logFileTxt, "')\n"), file=script, sep="", append=FALSE) - if(!debug) cat("quit ()\n", file=script, append=TRUE) + if(!debug) cat("modelQuit('y')\n", file=script, append=TRUE) - sims.files <- paste("coda", 1:n.chains, ".txt", sep="") + sims.files <- paste(coda, "CODAchain", 1:n.chains, ".txt", sep="") for(i in 1:n.chains) - cat("WinBUGS did not run correctly.\n", file=sims.files[i], append=FALSE) + cat("OpenBUGS did not run correctly.\n", file=sims.files[i], append=FALSE) } Modified: trunk/R2OpenBUGS/R/bugs.sims.R =================================================================== --- trunk/R2WinBUGS/R/bugs.sims.R 2010-05-17 21:16:20 UTC (rev 159) +++ trunk/R2OpenBUGS/R/bugs.sims.R 2010-07-25 02:45:16 UTC (rev 160) @@ -2,9 +2,9 @@ function (parameters.to.save, n.chains, n.iter, n.burnin, n.thin, DIC=TRUE) { ## Read the simulations from Bugs into R, format them, and monitor convergence - sims.files <- paste ("coda", 1:n.chains, ".txt", sep="") + sims.files <- paste ("CODAchain", 1:n.chains, ".txt", sep="") ## read in the names of the parameters and the indices of their samples - index <- read.table("codaIndex.txt", header = FALSE, sep = "\t") + index <- read.table("CODAindex.txt", header = FALSE, sep = " ") ## in Splus, read.table interprets the first row of the file as row names, ## while in R it does not if(is.R()) { Modified: trunk/R2OpenBUGS/R/write.model.R =================================================================== --- trunk/R2WinBUGS/R/write.model.R 2010-05-17 21:16:20 UTC (rev 159) +++ trunk/R2OpenBUGS/R/write.model.R 2010-07-25 02:45:16 UTC (rev 160) @@ -10,7 +10,7 @@ } model.text <- gsub("%_%", "", model.text) if (!is.R()){ - ## In S-PLUS, scientific notation is different than it is in WinBUGS. + ## In S-PLUS, scientific notation is different than it is in OpenBUGS. ## Change the format of any numbers in scientific notation. model.text <- replaceScientificNotationS(model.text) @@ -52,7 +52,7 @@ replaceScientificNotationS <- function(text){ ## Change the format of any numbers in "text" that are in S-PLUS -## scientific notation to WinBUGS scientific notation +## scientific notation to OpenBUGS scientific notation ## First, handle the positive exponents ## Find the first instance This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: Rodney S. <rsp...@mc...> - 2010-05-24 20:58:42
|
I see that most of the recent posts (patches) have to do with BRUGS. Now, running BRUGS on OS X may be possible. Check out this new amazing software by Amit Singh. I suppose this is slightly off topic, but I don't know who else to share this information with. http://osxbook.com/software/xbinary/ -- Rodney Sparapani Center for Patient Care and Outcomes Research Sr. Biostatistician http://www.mcw.edu/pcor 4 wheels good, 2 wheels better! Medical College of Wisconsin (MCW) WWLD?: What Would Lombardi Do? Milwaukee, WI, USA |
From: Gregor G. <gre...@bf...> - 2010-05-21 21:58:06
|
Dear Nathan, On 21 May 2010 22:46, <ope...@po...> wrote: > I finally had a need today to get serious about getting Winbugs running on a > network of Linux systems. I had previously run into the infamous > "err:ole:CoGetClassObject" and "trap #101 OleClient.Model.Internalize" errors, > and Google provided no answers, but did turn up Martyn's doomful pronouncement > that WinBUGS under Wine has been broken since 2001. Another day of research, > however, turned up a simple solution: Install DCOM98. Worked like a charm. > Details here: > > http://www.ynform.org/w/Pub/WinbugsUnderWine Thank you for sharing this info. I have to add that there are several people (including me) that were able to run WinBUGS under wine (Linux and/or MacOSX) for quite some time! There was an anoyning warning message like fixme:keyboard:RegisterHotKey (0x1002a,13,0x00000002,3): stub fixme:ole:GetHGlobalFromILockBytes cbSize is 13824 err:ole:CoGetClassObject class {0003000a-0000-0000-c000-000000000046} not registered err:ole:CoGetClassObject class {0003000a-0000-0000-c000-000000000046} not registered err:ole:CoGetClassObject no class object {0003000a-0000-0000-c000-000000000046} could be created for context 0x3 but BUGS worked like charm! Regards, gg |
From: <chr...@us...> - 2010-05-17 21:16:26
|
Revision: 159 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=159&view=rev Author: chris-jackson Date: 2010-05-17 21:16:20 +0000 (Mon, 17 May 2010) Log Message: ----------- Added seed option to openbugs() Modified Paths: -------------- trunk/R2WinBUGS/R/openbugs.R Modified: trunk/R2WinBUGS/R/openbugs.R =================================================================== --- trunk/R2WinBUGS/R/openbugs.R 2010-05-17 20:04:29 UTC (rev 158) +++ trunk/R2WinBUGS/R/openbugs.R 2010-05-17 21:16:20 UTC (rev 159) @@ -49,7 +49,7 @@ try(file.copy(file.path(savedWD, data), data, overwrite = TRUE)) BRugs::modelData(data) BRugs::modelCompile(numChains) - if(!is.null(seed)) BRugs::modelSetSeed(newSeed=seed) + if(!is.null(seed)) BRugs::modelSetRN(seed) if(missing(inits) || is.null(inits)) { BRugs::modelGenInits() } else { @@ -66,7 +66,7 @@ BRugs::samplesSetThin(nThin) ## set the adaptive phases -## We do no longer have any Registry.txt file availabe, +## We do no longer have any Registry.txt file availabe, ## hence not resetting the adaptive phase any more. ## People should move to BRugs directly. # adaptivelines <- scan(system.file("OpenBUGS", "Bugs", "Rsrc", @@ -75,7 +75,7 @@ # factories <- sub(".adaptivePhase", "", # adaptivelines[grep("adaptivePhase",adaptivelines)]) # sapply(factories, BRugs::modelSetAP, max(0, nBurnin-1)) - if(getOption("BRugsVerbose")){ + if(getOption("BRugsVerbose")){ cat("Sampling has been started ...\n") flush.console() } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-17 20:04:36
|
Revision: 158 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=158&view=rev Author: chris-jackson Date: 2010-05-17 20:04:29 +0000 (Mon, 17 May 2010) Log Message: ----------- Changed modelSet/GetSeed, currentValues, modelModules, modelAllocatedMemory to modelSet/GetRN, infoNodeValues, infoModules, infoMemory to be consistent with latest OpenBUGS GUI scripting commands. Assume these functions aren't important enough to worry about deprecating them for a while before removing them. Added new functions infoNodeMethods, infoNodeTypes, infoUpdatersbyName, infoUpdatersbyDepth. Modified Paths: -------------- trunk/BRugs/NAMESPACE trunk/BRugs/R/BRugsFit.R trunk/BRugs/man/BRugsFit.Rd trunk/BRugs/man/set.values.Rd Added Paths: ----------- trunk/BRugs/R/info.memory.R trunk/BRugs/R/info.modules.R trunk/BRugs/R/info.node.R trunk/BRugs/R/info.updaters.R trunk/BRugs/R/model.getRN.R trunk/BRugs/R/model.setRN.R trunk/BRugs/man/info.memory.Rd trunk/BRugs/man/info.modules.Rd trunk/BRugs/man/info.node.Rd trunk/BRugs/man/info.updaters.Rd trunk/BRugs/man/model.RN.Rd Removed Paths: ------------- trunk/BRugs/R/current.values.R trunk/BRugs/R/model.allocatedMemory.R trunk/BRugs/R/model.get.seed.R trunk/BRugs/R/model.modules.R trunk/BRugs/R/model.set.seed.R trunk/BRugs/man/current.values.Rd trunk/BRugs/man/model.allocatedMemory.Rd trunk/BRugs/man/model.modules.Rd trunk/BRugs/man/model.seed.Rd Modified: trunk/BRugs/NAMESPACE =================================================================== --- trunk/BRugs/NAMESPACE 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/NAMESPACE 2010-05-17 20:04:29 UTC (rev 158) @@ -1,14 +1,15 @@ useDynLib(BRugs) importFrom(coda, mcmc, mcmc.list) -export(BRugsFit, bugsData, bugsInits, buildMCMC, currentValues, +export(BRugsFit, bugsData, bugsInits, buildMCMC, dicClear, dicSet, dicStats, getNumChains, help.BRugs, help.WinBUGS, +infoMemory,infoModules,infoNodeValues,infoNodeMethods,infoNodeTypes, +infoUpdatersbyName,infoUpdatersbyDepth, modelAdaptivePhase, modelCheck, modelCompile, modelData, -modelGenInits, modelGetSeed, modelInits, modelIteration, -modelModules, modelNames, modelPrecision, modelSaveState, -modelSetAP, modelSetIts, modelSetOR, modelSetSeed, +modelGenInits, modelGetRN, modelInits, modelIteration, +modelNames, modelPrecision, modelSaveState, +modelSetAP, modelSetIts, modelSetOR, modelSetRN, modelUpdate, modelEnable, modelDisable, -modelEnableDynamic, modelDisableDynamic, plotAutoC, plotBgr, plotDensity, plotHistory, ranksClear, ranksSet, ranksStats, samplesAutoC, samplesBgr, samplesClear, samplesCoda, Modified: trunk/BRugs/R/BRugsFit.R =================================================================== --- trunk/BRugs/R/BRugsFit.R 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/R/BRugsFit.R 2010-05-17 20:04:29 UTC (rev 158) @@ -25,7 +25,7 @@ data <- bugsData(data, digits = digits) modelData(data) modelCompile(numChains) - if(!is.null(seed)) modelSetSeed(seed) + if(!is.null(seed)) modelSetRN(seed) if(!missing(inits)){ if(is.list(inits) || is.function(inits)) inits <- bugsInits(inits = inits, numChains = numChains, digits = digits) Deleted: trunk/BRugs/R/current.values.R =================================================================== --- trunk/BRugs/R/current.values.R 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/R/current.values.R 2010-05-17 20:04:29 UTC (rev 158) @@ -1,16 +0,0 @@ -"currentValues" <- -function(nodeLabel) -# Get current value of node -{ - nodeLabel <- as.character(nodeLabel) - command <- "BugsRobjects.SetVariable" - len <- nchar(command) - .C("CharArray", command, as.integer(len), nodeLabel, nchar(nodeLabel), integer(1), PACKAGE="BRugs") - command <- "BugsRobjects.GetSize" - nodeSize <- .Integer(command) - if(nodeSize == -1) - stop(nodeLabel, " is not a node in BUGS model") - command <- "BugsRobjects.GetValues" - .C("RealArray", command, nchar(command), as.double(rep(NA, nodeSize)), - as.integer(nodeSize), integer(1), NAOK = TRUE, PACKAGE="BRugs")[[3]] -} Added: trunk/BRugs/R/info.memory.R =================================================================== --- trunk/BRugs/R/info.memory.R (rev 0) +++ trunk/BRugs/R/info.memory.R 2010-05-17 20:04:29 UTC (rev 158) @@ -0,0 +1,9 @@ +"infoMemory" <- + function(){ + command <- "BugsEmbed.AllocatedMemory" + res <- .CmdInterpreter(command) + buffer <- file.path(tempdir(), "buffer.txt") + res <- readLines(buffer) + mem <- as.numeric(gsub("^([0-9]+).+", "\\1", res)) + mem + } Added: trunk/BRugs/R/info.modules.R =================================================================== --- trunk/BRugs/R/info.modules.R (rev 0) +++ trunk/BRugs/R/info.modules.R 2010-05-17 20:04:29 UTC (rev 158) @@ -0,0 +1,13 @@ +"infoModules" <- + function() + # List loaded OpenBUGS components +{ + command <- "BugsEmbed.Modules" + .CmdInterpreter(command) + buffer <- file.path(tempdir(), "buffer.txt") + result <- read.fwf(buffer, c(50, 12, 12, 12, 12, 10), skip = 1, as.is=TRUE) + for(i in c(1,4,5,6)) + result[,i] <- gsub(" ", "", result[,i]) + names(result) <- c("Module", "Clients", "Version", "Maintainer", "Compiled", "Loaded") + return(result) +} Added: trunk/BRugs/R/info.node.R =================================================================== --- trunk/BRugs/R/info.node.R (rev 0) +++ trunk/BRugs/R/info.node.R 2010-05-17 20:04:29 UTC (rev 158) @@ -0,0 +1,40 @@ +"infoNodeValues" <- +function(nodeLabel) +# Get current value of node +{ + nodeLabel <- as.character(nodeLabel) + command <- "BugsRobjects.SetVariable" + len <- nchar(command) + .C("CharArray", command, as.integer(len), nodeLabel, nchar(nodeLabel), integer(1), PACKAGE="BRugs") + command <- "BugsRobjects.GetSize" + nodeSize <- .Integer(command) + if(nodeSize == -1) + stop(nodeLabel, " is not a node in BUGS model") + command <- "BugsRobjects.GetValues" + .C("RealArray", command, nchar(command), as.double(rep(NA, nodeSize)), + as.integer(nodeSize), integer(1), NAOK = TRUE, PACKAGE="BRugs")[[3]] +} + +infoNodeMethods <- function(nodeLabel) +{ + nodeName <- sQuote(nodeLabel) + command <- paste("BugsEmbed.SetNode(",nodeName,"); BugsEmbed.Methods"); + .CmdInterpreter(command) + buffer <- file.path(tempdir(), "buffer.txt") + result <- read.fwf(buffer, c(25, 25, 25, 25), skip = 1, as.is=TRUE, col.names=c("Node","Type", "Size", "Depth")) + for (i in 1:2) + result[,i] <- gsub(" ", "", result[,i]) + result +} + +infoNodeTypes <- function(nodeLabel) +{ + nodeName <- sQuote(nodeLabel) + command <- paste("BugsEmbed.SetNode(",nodeName,"); BugsEmbed.Types"); + .CmdInterpreter(command) + buffer <- file.path(tempdir(), "buffer.txt") + result <- read.fwf(buffer, c(25, 25), skip = 1, as.is=TRUE, col.names=c("Node","Type")) + for (i in 1:2) + result[,i] <- gsub(" ", "", result[,i]) + result +} Added: trunk/BRugs/R/info.updaters.R =================================================================== --- trunk/BRugs/R/info.updaters.R (rev 0) +++ trunk/BRugs/R/info.updaters.R 2010-05-17 20:04:29 UTC (rev 158) @@ -0,0 +1,28 @@ + +## display updaters sorted by node name +infoUpdatersbyName <- function() +{ + command <- "BugsEmbed.NotCompiledGuard; BugsEmbed.UpdatersByName" + .CmdInterpreter(command) + buffer <- file.path(tempdir(), "Updater types.txt") + result <- read.fwf(buffer, c(25, 50, 10, 10), skip = 1, as.is=TRUE, + row.names=1, col.names=c("Node","Type", "Size","Depth")) + for (i in 1:2) + result[,i] <- gsub(" ", "", result[,i]) + rownames(result) <- gsub(" ", "", rownames(result)) + result +} + +## display updaters sorted by node depth in graph +infoUpdatersbyDepth <- function() +{ + command <- "BugsEmbed.NotCompiledGuard; BugsEmbed.UpdatersByDepth" + .CmdInterpreter(command) + buffer <- file.path(tempdir(), "Updater types.txt") + result <- read.fwf(buffer, c(25, 50, 10, 10), skip = 1, as.is=TRUE, + row.names=1, col.names=c("Node","Type", "Size","Depth")) + for (i in 1:2) + result[,i] <- gsub(" ", "", result[,i]) + rownames(result) <- gsub(" ", "", rownames(result)) + result +} Deleted: trunk/BRugs/R/model.allocatedMemory.R =================================================================== --- trunk/BRugs/R/model.allocatedMemory.R 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/R/model.allocatedMemory.R 2010-05-17 20:04:29 UTC (rev 158) @@ -1,9 +0,0 @@ -"modelAllocatedMemory" <- - function(){ - command <- "BugsEmbed.AllocatedMemory" - res <- .CmdInterpreter(command) - buffer <- file.path(tempdir(), "buffer.txt") - res <- readLines(buffer) - mem <- as.numeric(gsub("^([0-9]+).+", "\\1", res)) - mem - } Deleted: trunk/BRugs/R/model.get.seed.R =================================================================== --- trunk/BRugs/R/model.get.seed.R 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/R/model.get.seed.R 2010-05-17 20:04:29 UTC (rev 158) @@ -1,7 +0,0 @@ -"modelGetSeed" <- -function() -# Get the seed of random number generator -{ - command <- "BugsEmbed.preSet" - .Integer(command) -} Added: trunk/BRugs/R/model.getRN.R =================================================================== --- trunk/BRugs/R/model.getRN.R (rev 0) +++ trunk/BRugs/R/model.getRN.R 2010-05-17 20:04:29 UTC (rev 158) @@ -0,0 +1,7 @@ +"modelGetRN" <- +function() +# Get the seed of random number generator +{ + command <- "BugsEmbed.preSet" + .Integer(command) +} Deleted: trunk/BRugs/R/model.modules.R =================================================================== --- trunk/BRugs/R/model.modules.R 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/R/model.modules.R 2010-05-17 20:04:29 UTC (rev 158) @@ -1,13 +0,0 @@ -"modelModules" <- -function() -# List loaded OpenBUGS components -{ - command <- "BugsEmbed.Modules" - .CmdInterpreter(command) - buffer <- file.path(tempdir(), "buffer.txt") - result <- read.fwf(buffer, c(50, 12, 12, 12, 12, 10), skip = 1, as.is=TRUE) - for(i in c(1,4,5,6)) - result[,i] <- gsub(" ", "", result[,i]) - names(result) <- c("Module", "Clients", "Version", "Maintainer", "Compiled", "Loaded") - return(result) -} Deleted: trunk/BRugs/R/model.set.seed.R =================================================================== --- trunk/BRugs/R/model.set.seed.R 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/R/model.set.seed.R 2010-05-17 20:04:29 UTC (rev 158) @@ -1,14 +0,0 @@ -"modelSetSeed" <- -function(state) -# Set the seed of random number generator -{ - if(!state %in% 1:14) - stop("state must be an integer from 1 to 14") - newSeed <- as.integer(state) - command <- paste("BugsEmbed.SetRNGuard; BugsEmbed.SetRNState(", state, ")" ) - res <- .CmdInterpreter(command)[[3]] - if(!res){ - if(getOption("BRugsVerbose")) - message("Random number generator state successfully set") - }else stop("Setting random number generator state returned with an error.") -} Added: trunk/BRugs/R/model.setRN.R =================================================================== --- trunk/BRugs/R/model.setRN.R (rev 0) +++ trunk/BRugs/R/model.setRN.R 2010-05-17 20:04:29 UTC (rev 158) @@ -0,0 +1,14 @@ +"modelSetRN" <- +function(state) +# Set the seed of random number generator +{ + if(!state %in% 1:14) + stop("state must be an integer from 1 to 14") + state <- as.integer(state) + command <- paste("BugsEmbed.SetRNGuard; BugsEmbed.SetRNState(", state, ")" ) + res <- .CmdInterpreter(command)[[3]] + if(!res){ + if(getOption("BRugsVerbose")) + message("Random number generator state successfully set") + }else stop("Setting random number generator state returned with an error.") +} Modified: trunk/BRugs/man/BRugsFit.Rd =================================================================== --- trunk/BRugs/man/BRugsFit.Rd 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/man/BRugsFit.Rd 2010-05-17 20:04:29 UTC (rev 158) @@ -1,4 +1,4 @@ -\name{BRugsFit} +\name{BRugsFit} \alias{BRugsFit} \title{BRugs' meta function} \description{This function takes model, data and starting values as input and automatically runs a simulation in BRugs.} @@ -9,13 +9,13 @@ BRugsVerbose = getOption("BRugsVerbose")) } \arguments{ -\item{modelFile}{File containing the model written in OpenBUGS code, +\item{modelFile}{File containing the model written in OpenBUGS code, an R function that contains a BUGS model that is written to a temporary model file (see \code{\link{tempfile}}) using \code{\link{writeModel}}.} -\item{data}{Either a named list (names corresponding to variable names in the \code{modelFile}) +\item{data}{Either a named list (names corresponding to variable names in the \code{modelFile}) of the data for the OpenBUGS model, \emph{or} a vector or list of the names of the data objects used by the model. In these cases data are written into a file \file{data.txt} into the temporary directory of the current R session. - + If a filename of an existing file is given, data are read from that file.} \item{inits}{A list with \code{numChains} elements; each element of the list is itself a list of starting values for the OpenBUGS model, \emph{or} @@ -33,29 +33,29 @@ If \code{TRUE}, an \code{\link[coda]{mcmc.list}} object as known from the \pkg{coda} package is returned.} \item{DIC}{Logical, whether to calculate and return the DIC.} \item{working.directory}{Sets working directory during execution of this function; - \code{data}, \code{inits} and other files are written to / read from this directory if no other directory + \code{data}, \code{inits} and other files are written to / read from this directory if no other directory is explicitly given in those arguments. If \code{NULL}, the current working directory is chosen.} \item{digits}{Number of significant digits used for OpenBUGS input, see \code{\link{formatC}}.} -\item{seed}{Positive non-zero integer value(s) to set seed for random number - generator - default is no seed (see \code{\link{modelSetSeed}}).} -\item{BRugsVerbose}{Logical, whether BRugs is supposed to be verbose. +\item{seed}{Integer value from 1 to 14 defining the state of the random number + generator - default is to not specify the state (see \code{\link{modelSetRN}}).} +\item{BRugsVerbose}{Logical, whether BRugs is supposed to be verbose. This can be controlled for the whole BRugs package by by the option \sQuote{BRugsVerbose} (see \code{\link{options}}) which is set to \code{TRUE} by default.} } -\value{If \code{coda} is set to \kbd{TRUE}, an \code{\link[coda]{mcmc.list}} object as known from the \pkg{coda} package is returned, +\value{If \code{coda} is set to \kbd{TRUE}, an \code{\link[coda]{mcmc.list}} object as known from the \pkg{coda} package is returned, otherwise a list containg components \item{Stats}{A data frame containing sample statistics. See \code{\link{samplesStats}}.} \item{DIC}{The DIC statistics, if \code{DIC=TRUE}, else \code{NULL}. See \code{\link{dicStats}}.} } -\seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}. - Andrew Gelman proposes some \code{print} and \code{plot} methods that can be accessed by the +\seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}. + Andrew Gelman proposes some \code{print} and \code{plot} methods that can be accessed by the \code{openbugs} (and \code{bugs}) and \code{as.bugs.array} functions in the CRAN package \pkg{R2WinBUGS}.} \examples{ -BRugsFit(data = "ratsdata.txt", inits = "ratsinits.txt", - para = c("alpha", "beta"), modelFile = "ratsmodel.txt", - numChains = 1, - working.directory = system.file("OpenBUGS", "Examples", +BRugsFit(data = "ratsdata.txt", inits = "ratsinits.txt", + para = c("alpha", "beta"), modelFile = "ratsmodel.txt", + numChains = 1, + working.directory = system.file("OpenBUGS", "Examples", package = "BRugs")) } \keyword{interface} Deleted: trunk/BRugs/man/current.values.Rd =================================================================== --- trunk/BRugs/man/current.values.Rd 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/man/current.values.Rd 2010-05-17 20:04:29 UTC (rev 158) @@ -1,16 +0,0 @@ -\name{currentValues} -\alias{currentValues} -\title{Last sampled values} -\description{This function returns the current (last sampled) values of a variable.} -\usage{ -currentValues(nodeLabel) -} -\arguments{ - \item{nodeLabel}{Character vector of length 1, name of a variable in the model.} -} -\value{ -Vector of the current (last sampled) values of a variable. -} -\seealso{\code{\link{setValues}}, \code{\link{BRugs}}, \code{\link{help.WinBUGS}}} -\keyword{interface} - Added: trunk/BRugs/man/info.memory.Rd =================================================================== --- trunk/BRugs/man/info.memory.Rd (rev 0) +++ trunk/BRugs/man/info.memory.Rd 2010-05-17 20:04:29 UTC (rev 158) @@ -0,0 +1,12 @@ +\name{infoMemory} +\alias{infoMemory} +\title{Show memory usage} +\description{Shows the amount of memory allocated to OpenBUGS} +\usage{ +infoMemory() +} +\value{ + Amount of memory allocated to OpenBUGS, in bytes. +} +\seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}} +\keyword{interface} Added: trunk/BRugs/man/info.modules.Rd =================================================================== --- trunk/BRugs/man/info.modules.Rd (rev 0) +++ trunk/BRugs/man/info.modules.Rd 2010-05-17 20:04:29 UTC (rev 158) @@ -0,0 +1,11 @@ +\name{infoModules} +\alias{infoModules} +\title{Loaded modules} +\description{Displays all the modules (dynamic link libraries) in use.} +\usage{ +infoModules() +} +\value{Dataframe containing information on all the modules (dynamic link libraries) in use.} +\seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}} +\keyword{interface} + Added: trunk/BRugs/man/info.node.Rd =================================================================== --- trunk/BRugs/man/info.node.Rd (rev 0) +++ trunk/BRugs/man/info.node.Rd 2010-05-17 20:04:29 UTC (rev 158) @@ -0,0 +1,28 @@ +\name{infoNode} +\alias{infoNodeValues} +\alias{infoNodeMethods} +\alias{infoNodeTypes} +\title{Node information} +\description{List current values, data types and samplers corresponding to a variable.} +\usage{ +infoNodeValues(nodeLabel) +infoNodeMethods(nodeLabel) +infoNodeTypes(nodeLabel) +} +\arguments{ + \item{nodeLabel}{Character vector of length 1, name of a variable in the model.} +} +\value{ + \code{infoNodeValues} returns a vector of the current (last sampled) + values of a variable. + + \code{infoNodeMethods} returns a data frame listing the method used + internally by OpenBUGS to sample values from the full conditional + distribution of the node. + + \code{infoNodeTypes} returns a data frame listing the OpenBUGS data + type which represents each node internally. For example, stochastic + nodes with normal priors are of type \code{GraphNormal.StdNode}. +} +\seealso{\code{\link{setValues}}, \code{\link{BRugs}}, \code{\link{help.WinBUGS}}} +\keyword{interface} Added: trunk/BRugs/man/info.updaters.Rd =================================================================== --- trunk/BRugs/man/info.updaters.Rd (rev 0) +++ trunk/BRugs/man/info.updaters.Rd 2010-05-17 20:04:29 UTC (rev 158) @@ -0,0 +1,25 @@ +\name{infoUpdaters} +\alias{infoUpdatersbyName} +\alias{infoUpdatersbyDepth} +\title{Information on MCMC updaters} +\description{List the MCMC sampling algorithms in use by the current model.} +\usage{ +infoUpdatersbyName() +infoUpdatersbyDepth() +} +\value{ + A data frame listing the MCMC updating algorithms used for each + stochastic node in the model. + + For block updating algorithms, the first component in the block is + shown followed by the other components of the block in angle brackets. + For vector nodes, only the first element is shown. + + \code{infoUpdatersbyName} sorts the nodes alphabetically. + + \code{infoUpdatersbyDepth} sorts the nodes in their reverse topological + order in the graphical model. Nodes which are forward sampled have a + negative depth. +} +\seealso{\code{\link{infoNodeMethods}},\code{\link{BRugs}}, +\code{\link{help.WinBUGS}}} \keyword{interface} Added: trunk/BRugs/man/model.RN.Rd =================================================================== --- trunk/BRugs/man/model.RN.Rd (rev 0) +++ trunk/BRugs/man/model.RN.Rd 2010-05-17 20:04:29 UTC (rev 158) @@ -0,0 +1,23 @@ +\name{modelRN} +\alias{modelSetRN} +\alias{modelGetRN} +\title{State of Random Number Generator} +\description{These functions set/return the starting state of the random number generator.} +\usage{ +modelSetRN(state) +modelGetRN() +} +\arguments{ + \item{state}{An integer from 1 to 14. The internal state of the OpenBUGS random number generator can be set to one of 14 predefined states. Each predefined state is \eqn{10^12}{10^12} draws apart to avoid overlap in random number sequences.} +} +\details{Warning: \code{modelSetRN} must not be used before + \code{\link{modelCompile}} has been executed successfully! + The state can be changed after initial values are generated + but before updates have been performed, however, this is not recommended. +} +\seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}} +\keyword{interface} +\concept{update} +\concept{iteration} +\concept{seed} +\concept{random} Deleted: trunk/BRugs/man/model.allocatedMemory.Rd =================================================================== --- trunk/BRugs/man/model.allocatedMemory.Rd 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/man/model.allocatedMemory.Rd 2010-05-17 20:04:29 UTC (rev 158) @@ -1,13 +0,0 @@ -\name{modelAllocatedMemory} -\alias{modelAllocatedMemory} -\title{Show memory usage} -\description{Shows the amount of memory allocated to OpenBUGS} -\usage{ -modelAllocatedMemory() -} -\value{ - Amount of memory allocated to OpenBUGS, in bytes. -} -\seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}} -\keyword{interface} - Deleted: trunk/BRugs/man/model.modules.Rd =================================================================== --- trunk/BRugs/man/model.modules.Rd 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/man/model.modules.Rd 2010-05-17 20:04:29 UTC (rev 158) @@ -1,11 +0,0 @@ -\name{modelModules} -\alias{modelModules} -\title{Loaded modules} -\description{Displays all the modules (dynamic link libraries) in use.} -\usage{ -modelModules() -} -\value{Dataframe containing information on all the modules (dynamic link libraries) in use.} -\seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}} -\keyword{interface} - Deleted: trunk/BRugs/man/model.seed.Rd =================================================================== --- trunk/BRugs/man/model.seed.Rd 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/man/model.seed.Rd 2010-05-17 20:04:29 UTC (rev 158) @@ -1,23 +0,0 @@ -\name{modelSeed} -\alias{modelSetSeed} -\alias{modelGetSeed} -\title{Seed of Random Number Generator} -\description{These functions set/return the seed of the random number generator.} -\usage{ -modelSetSeed(state) -modelGetSeed() -} -\arguments{ - \item{state}{An integer from 1 to 14. The internal state of the OpenBUGS random number generator can be set to one of 14 predefined states. Each predefined state is \eqn{10^12}{10^12} draws apart to avoid overlap in random number sequences.} -} -\details{Warning: \code{modelSetSeed} must not be used before - \code{\link{modelCompile}} has been executed successfully! - The state can be changed after initial values are generated - but before updates have been performed, however, this is not recommended. -} -\seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}} -\keyword{interface} -\concept{update} -\concept{iteration} -\concept{seed} -\concept{random} Modified: trunk/BRugs/man/set.values.Rd =================================================================== --- trunk/BRugs/man/set.values.Rd 2010-05-17 19:57:28 UTC (rev 157) +++ trunk/BRugs/man/set.values.Rd 2010-05-17 20:04:29 UTC (rev 158) @@ -8,13 +8,13 @@ } \arguments{ \item{nodeLabel}{Character vector of length 1, name of a vector node in the model.} - \item{values}{The values to be set, generated, e.g., by \code{\link{currentValues}}.} + \item{values}{The values to be set, generated, e.g., by \code{\link{infoNodeValues}}.} } \details{ -\code{\link{currentValues}} of a model can be stored in order to be used as initial values. +Current values of a node can be stored to be used later as initial values. } \value{The number of values set.} -\seealso{\code{\link{currentValues}}, \code{\link{BRugs}}, \code{\link{help.WinBUGS}}} +\seealso{\code{\link{infoNodeValues}}, \code{\link{BRugs}}, \code{\link{help.WinBUGS}}} \keyword{interface} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-17 19:57:35
|
Revision: 157 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=157&view=rev Author: chris-jackson Date: 2010-05-17 19:57:28 +0000 (Mon, 17 May 2010) Log Message: ----------- Added new tests: examples.R (a selection of the official examples which take a few seconds in total to run - posterior means are compared to the results in examples.stats.R) and functions.R (including assertion tests for all of the user-visible functions). Added Paths: ----------- trunk/BRugs/tests/examples.R trunk/BRugs/tests/examples.stats.R trunk/BRugs/tests/functions.R Added: trunk/BRugs/tests/examples.R =================================================================== --- trunk/BRugs/tests/examples.R (rev 0) +++ trunk/BRugs/tests/examples.R 2010-05-17 19:57:28 UTC (rev 157) @@ -0,0 +1,40 @@ +library(BRugs) + +## Selected examples which take a few seconds in total to run + +test.models <- c("Air", "Asia", "Beetles", "BiRats", "Camel", + "Dugongs", "Dyes", "Equiv", "Eyes", + "Line", "OtreesMVN", "Rats", "Stacks", + "Surgical", "Surgicalrand") + +test.params <- list(Air = c("X", "theta"), + Asia = c("bronchitis", "either", "lung.cancer"), + Beetles = c("alpha", "beta", "rhat"), + BiRats = c("mu.beta", "sigma"), + Camel = c("Sigma2", "rho", "tau"), + Dugongs = c("U3","alpha", "beta", "gamma", "sigma"), + Dyes = c("sigma2.btw", "sigma2.with", "theta"), + Equiv = c("equiv", "mu", "phi", "pi","sigma1", "sigma2", "theta"), + Eyes = c("P", "lambda", "sigma"), + Line = c("alpha", "beta", "sigma"), + OtreesMVN = c("mu","sigma", "sigmaC"), + Rats = c("alpha0", "beta.c", "sigma"), + Stacks = c("b", "b0", "outlier[21]","outlier[3]", "outlier[4]", "sigma"), + Surgical = "p", + Surgicalrand = c("p","pop.mean", "sigma") + ) + +test.modelfile = paste(test.models,"model.txt",sep="") +test.datafile = paste(test.models,"data.txt",sep="") +test.inits = paste(test.models,"inits.txt",sep="") + +### Test for posterior means within 1 percent of previously saved values + +res.true <- dget(file="examples.stats.R") +for (i in seq(along=test.models)) { + fit <- BRugsFit(data=test.datafile[i], inits=test.inits[i], modelFile=test.modelfile[i], para=test.params[[test.models[i]]], + nBurnin=5000, nIter=20000, nThin=1, numChains=1, seed=1, + working.directory=system.file("OpenBUGS", "Examples", package = "BRugs") + ) + stopifnot(isTRUE(all.equal(fit$Stats$mean, res.true[[i]]$Stats$mean, tol=1e-02))) +} Added: trunk/BRugs/tests/examples.stats.R =================================================================== --- trunk/BRugs/tests/examples.stats.R (rev 0) +++ trunk/BRugs/tests/examples.stats.R 2010-05-17 19:57:28 UTC (rev 157) @@ -0,0 +1,215 @@ +list(structure(list(Stats = structure(list(mean = c(13.45, 27.41, +40.91, -0.8844, 0.0448), sd = c(8.677, 7.465, 8.811, 2.831, 0.1047 +), MC_error = c(0.143, 0.08436, 0.1297, 0.04967, 0.001829), val2.5pc = c(-3.828, +12.88, 23.57, -4.62, -0.01401), median = c(13.52, 27.32, 40.89, +-0.67, 0.03728), val97.5pc = c(30.29, 42.38, 58.25, 0.6397, 0.1856 +), start = c(5001L, 5001L, 5001L, 5001L, 5001L), sample = c(20000L, +20000L, 20000L, 20000L, 20000L)), .Names = c("mean", "sd", "MC_error", +"val2.5pc", "median", "val97.5pc", "start", "sample"), row.names = c("X[1]", +"X[2]", "X[3]", "theta[1]", "theta[2]"), class = "data.frame"), + DIC = structure(list(Dbar = c(14.2, 14.2), Dhat = c(11.62, + 11.62), DIC = c(16.79, 16.79), pD = c(2.583, 2.583)), .Names = c("Dbar", + "Dhat", "DIC", "pD"), class = "data.frame", row.names = c("y", + "total"))), .Names = c("Stats", "DIC")), structure(list(Stats = structure(list( + mean = c(1.808, 1.177, 1.095), sd = c(0.3942, 0.3816, 0.293 + ), MC_error = c(0.004268, 0.004489, 0.003713), val2.5pc = c(1, + 1, 1), median = c(2, 1, 1), val97.5pc = c(2, 2, 2), start = c(5001L, + 5001L, 5001L), sample = c(20000L, 20000L, 20000L)), .Names = c("mean", +"sd", "MC_error", "val2.5pc", "median", "val97.5pc", "start", +"sample"), row.names = c("bronchitis", "either", "lung.cancer" +), class = "data.frame"), DIC = NULL), .Names = c("Stats", "DIC" +)), structure(list(Stats = structure(list(mean = c(-60.79, 34.31, +3.567, 9.951, 22.51, 33.9, 50.05, 53.22, 59.15, 58.69), sd = c(5.147, +2.894, 0.9514, 1.676, 2.09, 1.761, 1.662, 1.114, 0.7424, 0.4299 +), MC_error = c(0.0498, 0.02805, 0.008182, 0.01405, 0.01656, +0.01414, 0.01468, 0.01026, 0.006914, 0.004009), val2.5pc = c(-71.1, +28.75, 1.994, 6.945, 18.48, 30.4, 46.66, 50.84, 57.51, 57.7), + median = c(-60.69, 34.26, 3.465, 9.858, 22.48, 33.91, 50.09, + 53.29, 59.22, 58.74), val97.5pc = c(-50.91, 40.14, 5.707, + 13.5, 26.67, 37.27, 53.16, 55.19, 60.38, 59.36), start = c(5001L, + 5001L, 5001L, 5001L, 5001L, 5001L, 5001L, 5001L, 5001L, 5001L + ), sample = c(20000L, 20000L, 20000L, 20000L, 20000L, 20000L, + 20000L, 20000L, 20000L, 20000L)), .Names = c("mean", "sd", +"MC_error", "val2.5pc", "median", "val97.5pc", "start", "sample" +), row.names = c("alpha", "beta", "rhat[1]", "rhat[2]", "rhat[3]", +"rhat[4]", "rhat[5]", "rhat[6]", "rhat[7]", "rhat[8]"), class = "data.frame"), + DIC = structure(list(Dbar = c(39.42, 39.42), Dhat = c(37.43, + 37.43), DIC = c(41.4, 41.4), pD = c(1.987, 1.987)), .Names = c("Dbar", + "Dhat", "DIC", "pD"), class = "data.frame", row.names = c("r", + "total"))), .Names = c("Stats", "DIC")), structure(list(Stats = structure(list( + mean = c(106.6, 6.187, 6.147), sd = c(2.352, 0.1061, 0.4781 + ), MC_error = c(0.02256, 0.0009468, 0.006136), val2.5pc = c(101.9, + 5.978, 5.301), median = c(106.5, 6.187, 6.112), val97.5pc = c(111.2, + 6.398, 7.173), start = c(5001L, 5001L, 5001L), sample = c(20000L, + 20000L, 20000L)), .Names = c("mean", "sd", "MC_error", "val2.5pc", +"median", "val97.5pc", "start", "sample"), row.names = c("mu.beta[1]", +"mu.beta[2]", "sigma"), class = "data.frame"), DIC = structure(list( + Dbar = c(969.6, 969.6), Dhat = c(919.6, 919.6), DIC = c(1020, + 1020), pD = c(50.01, 50.01)), .Names = c("Dbar", "Dhat", +"DIC", "pD"), class = "data.frame", row.names = c("Y", "total" +))), .Names = c("Stats", "DIC")), structure(list(Stats = structure(list( + mean = c(3.242, 0.008511, 0.008511, 3.199, 0.001476, 0.8453, + -0.004605, -0.004605, 0.8579), sd = c(2.101, 2.492, 2.492, + 2.104, 0.6561, 0.5059, 0.7047, 0.7047, 0.509), MC_error = c(0.0255, + 0.08255, 0.08255, 0.02649, 0.02443, 0.007006, 0.02403, 0.02403, + 0.007312), val2.5pc = c(1.14, -4.754, -4.754, 1.104, -0.9073, + 0.2191, -1.398, -1.398, 0.2237), median = c(2.691, -0.01866, + -0.01866, 2.652, -0.007769, 0.7261, 0.003158, 0.003158, 0.7381 + ), val97.5pc = c(8.551, 4.769, 4.769, 8.537, 0.9089, 2.119, + 1.398, 1.398, 2.163), start = c(5001L, 5001L, 5001L, 5001L, + 5001L, 5001L, 5001L, 5001L, 5001L), sample = c(20000L, 20000L, + 20000L, 20000L, 20000L, 20000L, 20000L, 20000L, 20000L)), .Names = c("mean", +"sd", "MC_error", "val2.5pc", "median", "val97.5pc", "start", +"sample"), row.names = c("Sigma2[1,1]", "Sigma2[1,2]", "Sigma2[2,1]", +"Sigma2[2,2]", "rho", "tau[1,1]", "tau[1,2]", "tau[2,1]", "tau[2,2]" +), class = "data.frame"), DIC = NULL), .Names = c("Stats", "DIC" +)), structure(list(Stats = structure(list(mean = c(1.859, 2.651, +0.9713, 0.8622, 0.09894), sd = c(0.265, 0.07082, 0.07689, 0.03177, +0.01488), MC_error = c(0.0146, 0.00389, 0.002055, 0.001754, 0.0002341 +), val2.5pc = c(1.332, 2.53, 0.8227, 0.7911, 0.07493), median = c(1.853, +2.642, 0.9703, 0.8645, 0.09724), val97.5pc = c(2.374, 2.803, +1.124, 0.9148, 0.133), start = c(5001L, 5001L, 5001L, 5001L, +5001L), sample = c(20000L, 20000L, 20000L, 20000L, 20000L)), .Names = c("mean", +"sd", "MC_error", "val2.5pc", "median", "val97.5pc", "start", +"sample"), row.names = c("U3", "alpha", "beta", "gamma", "sigma" +), class = "data.frame"), DIC = structure(list(Dbar = c(-49.1, +-49.1), Dhat = c(-52.96, -52.96), DIC = c(-45.25, -45.25), pD = c(3.852, +3.852)), .Names = c("Dbar", "Dhat", "DIC", "pD"), class = "data.frame", row.names = c("Y", +"total"))), .Names = c("Stats", "DIC")), structure(list(Stats = structure(list( + mean = c(2380, 2981, 1527), sd = c(8162, 1091, 22.42), MC_error = c(121.4, + 36.99, 0.3445), val2.5pc = c(0.01265, 1549, 1483), median = c(1382, + 2753, 1526), val97.5pc = c(10210, 5686, 1571), start = c(5001L, + 5001L, 5001L), sample = c(20000L, 20000L, 20000L)), .Names = c("mean", +"sd", "MC_error", "val2.5pc", "median", "val97.5pc", "start", +"sample"), row.names = c("sigma2.btw", "sigma2.with", "theta" +), class = "data.frame"), DIC = structure(list(Dbar = c(323.4, +323.4), Dhat = c(316.9, 316.9), DIC = c(329.9, 329.9), pD = c(6.475, +6.475)), .Names = c("Dbar", "Dhat", "DIC", "pD"), class = "data.frame", row.names = c("y", +"total"))), .Names = c("Stats", "DIC")), structure(list(Stats = structure(list( + mean = c(0.9978, 1.434, -0.008588, -0.1801, 0.1104, 0.1406, + 0.9928), sd = c(0.04685, 0.05495, 0.05196, 0.05179, 0.03345, + 0.05436, 0.05167), MC_error = c(0.0003252, 0.001275, 0.0003669, + 0.0003675, 0.0006507, 0.0009669, 0.0003686), val2.5pc = c(1, + 1.325, -0.1124, -0.2828, 0.06491, 0.04493, 0.8937), median = c(1, + 1.434, -0.008368, -0.1805, 0.1032, 0.1355, 0.9917), val97.5pc = c(1, + 1.542, 0.09495, -0.0747, 0.1924, 0.2671, 1.1), start = c(5001L, + 5001L, 5001L, 5001L, 5001L, 5001L, 5001L), sample = c(20000L, + 20000L, 20000L, 20000L, 20000L, 20000L, 20000L)), .Names = c("mean", +"sd", "MC_error", "val2.5pc", "median", "val97.5pc", "start", +"sample"), row.names = c("equiv", "mu", "phi", "pi", "sigma1", +"sigma2", "theta"), class = "data.frame"), DIC = structure(list( + Dbar = c(-33.27, -33.27), Dhat = c(-45.21, -45.21), DIC = c(-21.32, + -21.32), pD = c(11.94, 11.94)), .Names = c("Dbar", "Dhat", +"DIC", "pD"), class = "data.frame", row.names = c("Y", "total" +))), .Names = c("Stats", "DIC")), structure(list(Stats = structure(list( + mean = c(0.6032, 0.3968, 536.8, 548.9, 3.758), sd = c(0.08391, + 0.08391, 0.9152, 1.209, 0.6041), MC_error = c(0.00113, 0.00113, + 0.01592, 0.01913, 0.01316), val2.5pc = c(0.4339, 0.2372, + 535.1, 546.5, 2.919), median = c(0.6042, 0.3958, 536.7, 548.9, + 3.653), val97.5pc = c(0.7628, 0.5662, 538.6, 551.2, 5.259 + ), start = c(5001L, 5001L, 5001L, 5001L, 5001L), sample = c(20000L, + 20000L, 20000L, 20000L, 20000L)), .Names = c("mean", "sd", +"MC_error", "val2.5pc", "median", "val97.5pc", "start", "sample" +), row.names = c("P[1]", "P[2]", "lambda[1]", "lambda[2]", "sigma" +), class = "data.frame"), DIC = NULL), .Names = c("Stats", "DIC" +)), structure(list(Stats = structure(list(mean = c(2.995, 0.7968, +1.022), sd = c(0.5625, 0.3953, 0.7287), MC_error = c(0.004086, +0.002512, 0.009658), val2.5pc = c(1.916, 0.05661, 0.4119), median = c(2.997, +0.7993, 0.8279), val97.5pc = c(4.059, 1.541, 2.789), start = c(5001L, +5001L, 5001L), sample = c(20000L, 20000L, 20000L)), .Names = c("mean", +"sd", "MC_error", "val2.5pc", "median", "val97.5pc", "start", +"sample"), row.names = c("alpha", "beta", "sigma"), class = "data.frame"), + DIC = structure(list(Dbar = c(12.97, 12.97), Dhat = c(9.063, + 9.063), DIC = c(16.87, 16.87), pD = c(3.903, 3.903)), .Names = c("Dbar", + "Dhat", "DIC", "pD"), class = "data.frame", row.names = c("Y", + "total"))), .Names = c("Stats", "DIC")), structure(list(Stats = structure(list( + mean = c(5.264, 2.198, -5.881, 0.2585, 0.2708, 0.2283, 7.837 + ), sd = c(0.1339, 0.1666, 0.1437, 0.1155, 0.1379, 0.1102, + 1.19), MC_error = c(0.002003, 0.00395, 0.003601, 0.001239, + 0.002355, 0.002098, 0.02413), val2.5pc = c(4.996, 1.879, + -6.172, 0.1275, 0.1199, 0.1086, 5.91), median = c(5.264, + 2.196, -5.879, 0.2317, 0.2399, 0.2018, 7.699), val97.5pc = c(5.532, + 2.535, -5.602, 0.5434, 0.6071, 0.5034, 10.57), start = c(5001L, + 5001L, 5001L, 5001L, 5001L, 5001L, 5001L), sample = c(20000L, + 20000L, 20000L, 20000L, 20000L, 20000L, 20000L)), .Names = c("mean", +"sd", "MC_error", "val2.5pc", "median", "val97.5pc", "start", +"sample"), row.names = c("mu[1]", "mu[2]", "mu[3]", "sigma[1]", +"sigma[2]", "sigma[3]", "sigmaC"), class = "data.frame"), DIC = structure(list( + Dbar = c(242.7, 242.7), Dhat = c(229.9, 229.9), DIC = c(255.6, + 255.6), pD = c(12.83, 12.83)), .Names = c("Dbar", "Dhat", +"DIC", "pD"), class = "data.frame", row.names = c("Y", "total" +))), .Names = c("Stats", "DIC")), structure(list(Stats = structure(list( + mean = c(106.6, 6.186, 6.097), sd = c(3.629, 0.1074, 0.4656 + ), MC_error = c(0.02738, 0.0008775, 0.005451), val2.5pc = c(99.38, + 5.975, 5.271), median = c(106.6, 6.187, 6.065), val97.5pc = c(113.6, + 6.395, 7.094), start = c(5001L, 5001L, 5001L), sample = c(20000L, + 20000L, 20000L)), .Names = c("mean", "sd", "MC_error", "val2.5pc", +"median", "val97.5pc", "start", "sample"), row.names = c("alpha0", +"beta.c", "sigma"), class = "data.frame"), DIC = structure(list( + Dbar = c(967, 967), Dhat = c(912.7, 912.7), DIC = c(1021, + 1021), pD = c(54.36, 54.36)), .Names = c("Dbar", "Dhat", +"DIC", "pD"), class = "data.frame", row.names = c("Y", "total" +))), .Names = c("Stats", "DIC")), structure(list(Stats = structure(list( + mean = c(0.7154, 1.294, -0.1516, -39.93, 0.0104, 0.05455, + 0.3221, 3.389), sd = c(0.1418, 0.3861, 0.1655, 12.65, 0.1014, + 0.2271, 0.4673, 0.6247), MC_error = c(0.002215, 0.005965, + 0.001676, 0.1113, 0.0006987, 0.001789, 0.004462, 0.005228 + ), val2.5pc = c(0.4371, 0.5286, -0.4804, -65.13, 0, 0, 0, + 2.423), median = c(0.7154, 1.292, -0.1516, -39.98, 0, 0, + 0, 3.297), val97.5pc = c(0.9979, 2.062, 0.1764, -14.65, 0, + 1, 1, 4.841), start = c(5001L, 5001L, 5001L, 5001L, 5001L, + 5001L, 5001L, 5001L), sample = c(20000L, 20000L, 20000L, + 20000L, 20000L, 20000L, 20000L, 20000L)), .Names = c("mean", +"sd", "MC_error", "val2.5pc", "median", "val97.5pc", "start", +"sample"), row.names = c("b[1]", "b[2]", "b[3]", "b0", "outlier[3]", +"outlier[4]", "outlier[21]", "sigma"), class = "data.frame"), + DIC = structure(list(Dbar = c(110.3, 110.3), Dhat = c(105, + 105), DIC = c(115.5, 115.5), pD = c(5.265, 5.265)), .Names = c("Dbar", + "Dhat", "DIC", "pD"), class = "data.frame", row.names = c("Y", + "total"))), .Names = c("Stats", "DIC")), structure(list(Stats = structure(list( + mean = c(0.02045, 0.1263, 0.07463, 0.05796, 0.04218, 0.0707, + 0.06664, 0.1475, 0.07183, 0.09073, 0.1164, 0.06897), sd = c(0.01989, + 0.02722, 0.02387, 0.008142, 0.01376, 0.01815, 0.02014, 0.02405, + 0.01783, 0.02867, 0.01986, 0.01338), MC_error = c(0.0001314, + 0.0001809, 0.0001651, 5.562e-05, 0.000104, 0.0001297, 0.0001363, + 0.000159, 0.0001341, 0.0002174, 0.0001431, 7.827e-05), val2.5pc = c(0.0005114, + 0.07791, 0.03489, 0.04312, 0.01952, 0.03918, 0.03277, 0.1033, + 0.04117, 0.04322, 0.08045, 0.04527), median = c(0.01431, + 0.1245, 0.07223, 0.05761, 0.0408, 0.06934, 0.06457, 0.1462, + 0.07045, 0.08807, 0.1156, 0.0682), val97.5pc = c(0.07349, + 0.1833, 0.1272, 0.0748, 0.07277, 0.1099, 0.1107, 0.1975, + 0.1112, 0.1546, 0.158, 0.09749), start = c(5001L, 5001L, + 5001L, 5001L, 5001L, 5001L, 5001L, 5001L, 5001L, 5001L, 5001L, + 5001L), sample = c(20000L, 20000L, 20000L, 20000L, 20000L, + 20000L, 20000L, 20000L, 20000L, 20000L, 20000L, 20000L)), .Names = c("mean", +"sd", "MC_error", "val2.5pc", "median", "val97.5pc", "start", +"sample"), row.names = c("p[1]", "p[2]", "p[3]", "p[4]", "p[5]", +"p[6]", "p[7]", "p[8]", "p[9]", "p[10]", "p[11]", "p[12]"), class = "data.frame"), + DIC = structure(list(Dbar = c(62.74, 62.74), Dhat = c(52.3, + 52.3), DIC = c(73.17, 73.17), pD = c(10.43, 10.43)), .Names = c("Dbar", + "Dhat", "DIC", "pD"), class = "data.frame", row.names = c("r", + "total"))), .Names = c("Stats", "DIC")), structure(list(Stats = structure(list( + mean = c(0.05316, 0.103, 0.07054, 0.05926, 0.05167, 0.06909, + 0.06683, 0.1232, 0.07, 0.07816, 0.1021, 0.0685, 0.07273, + 0.4024), sd = c(0.01955, 0.02166, 0.0174, 0.00791, 0.01315, + 0.01487, 0.01597, 0.02253, 0.01458, 0.01988, 0.01755, 0.01166, + 0.01016, 0.1546), MC_error = c(0.0002498, 0.0002237, 0.0001453, + 8.046e-05, 0.0001714, 0.0001062, 0.0001437, 0.0002708, 0.0001184, + 0.0001472, 0.000178, 9.045e-05, 0.0001177, 0.002699), val2.5pc = c(0.01832, + 0.06674, 0.03992, 0.0446, 0.02813, 0.04269, 0.03834, 0.08309, + 0.04398, 0.04431, 0.07166, 0.04735, 0.05325, 0.1627), median = c(0.05232, + 0.101, 0.06922, 0.059, 0.05099, 0.0683, 0.06583, 0.1216, + 0.0691, 0.07615, 0.1009, 0.06801, 0.07254, 0.3812), val97.5pc = c(0.09456, + 0.1511, 0.1088, 0.07551, 0.07896, 0.1011, 0.1011, 0.1711, + 0.1012, 0.1223, 0.14, 0.09294, 0.0937, 0.7632), start = c(5001L, + 5001L, 5001L, 5001L, 5001L, 5001L, 5001L, 5001L, 5001L, 5001L, + 5001L, 5001L, 5001L, 5001L), sample = c(20000L, 20000L, 20000L, + 20000L, 20000L, 20000L, 20000L, 20000L, 20000L, 20000L, 20000L, + 20000L, 20000L, 20000L)), .Names = c("mean", "sd", "MC_error", +"val2.5pc", "median", "val97.5pc", "start", "sample"), row.names = c("p[1]", +"p[2]", "p[3]", "p[4]", "p[5]", "p[6]", "p[7]", "p[8]", "p[9]", +"p[10]", "p[11]", "p[12]", "pop.mean", "sigma"), class = "data.frame"), + DIC = structure(list(Dbar = c(65.97, 65.97), Dhat = c(57.49, + 57.49), DIC = c(74.45, 74.45), pD = c(8.479, 8.479)), .Names = c("Dbar", + "Dhat", "DIC", "pD"), class = "data.frame", row.names = c("r", + "total"))), .Names = c("Stats", "DIC"))) Added: trunk/BRugs/tests/functions.R =================================================================== --- trunk/BRugs/tests/functions.R (rev 0) +++ trunk/BRugs/tests/functions.R 2010-05-17 19:57:28 UTC (rev 157) @@ -0,0 +1,109 @@ +library(BRugs) +setwd(system.file("OpenBUGS", "Examples", package="BRugs")) + +### TEST ALL USER-LEVEL FUNCTIONS USING RATS EXAMPLE + +### Basic model setup and stats +modelCheck("ratsmodel.txt") +modelData("ratsdata.txt") +modelCompile(numChains=2) +modelSetRN(4) +stopifnot(modelGetRN()==4) +modelInits(rep("ratsinits.txt", 2)) +modelUpdate(1000) +samplesSet(c("alpha0", "alpha")) +summarySet(c("alpha0","alpha")) +ranksSet("alpha") +dicSet() +modelUpdate(1000) +stopifnot(samplesMonitors("*")[31]=="alpha0") +stopifnot(isTRUE(all.equal(samplesStats("*")["alpha0","mean"], 106.6))) +stopifnot(isTRUE(all.equal(dicStats()["total","DIC"],1021))) +stopifnot(isTRUE(all.equal(summaryStats("alpha0")["alpha0","mean"], 106.6))) +stopifnot(isTRUE(all.equal(as.numeric(ranksStats("alpha")[1,]), c(10,12,18)))) + +### Utilities +samplesSetBeg(1200); stopifnot(samplesGetBeg()==1200) +samplesSetEnd(1500); stopifnot(samplesGetEnd()==1500) +samplesSetFirstChain(2); stopifnot(samplesGetFirstChain()==2) +samplesSetLastChain(2); stopifnot(samplesGetLastChain()==2) +samplesSetThin(2); stopifnot(samplesGetThin()==2) +samplesSetBeg(1000) +samplesSetEnd(1000000) +samplesSetFirstChain(1) +samplesSetLastChain(2) +samplesSetThin(1) +stopifnot(samplesSize("alpha0")==2*1000) +stopifnot(length(samplesSample("alpha0"))==2*1000) +stopifnot(length(infoNodeValues("alpha"))==30) +stopifnot(BRugs:::dimensions("alpha")==1) +stopifnot(BRugs:::dimensions("alpha0")==0) +stopifnot(modelIteration()==2000) +stopifnot(all.equal(sort(modelNames()),sort(c("N", "T", "Y", "alpha", "alpha.c", "alpha.tau", "alpha0", "beta","beta.c", "beta.tau", "deviance", "mu", "sigma", "tau.c", "x","xbar")))) +modelPrecision(8) +stopifnot(nchar(as.character(samplesStats("alpha0")$mean))==9) +modelPrecision(4) +x <- infoNodeValues("alpha") +setValues("alpha", x-1) +stopifnot(isTRUE(all.equal(infoNodeValues("alpha"), x-1))) +stopifnot(modelAdaptivePhase()==-1) + +### Plots +stopifnot(all(dim(samplesHistory("alpha0", plot=interactive())[[1]])==c(1000,2))) +stopifnot(isTRUE(all.equal(samplesAutoC("alpha0", 1, plot=interactive())$alpha0$acf[1], 1))) +stopifnot(all(dim(samplesBgr("alpha0", plot=interactive())$alpha0)==c(50,4))) +stopifnot(isTRUE(all.equal(samplesCorrel("alpha[1]", "alpha[2]")[1,1], 0.007215))) +stopifnot(all(dim(samplesDensity("alpha", plot=interactive()))==c(7,30))) +stopifnot(all(dim(plotHistory("alpha0", plot=interactive())[[1]])==c(1000,2))) +stopifnot(isTRUE(all.equal(plotAutoC("alpha0", 1, plot=interactive())$acf[1], 1))) +stopifnot(all(dim(plotBgr("alpha0", plot=interactive()))==c(50,4))) +stopifnot(length(plotDensity("alpha0",plot=FALSE))==7) + +### Clearing +samplesClear("alpha") +stopifnot(samplesMonitors("*")=="alpha0") +stopifnot(samplesSize("alpha")==0) +dicClear() +summaryClear("*") + +## External and file access +samplesCoda("*" ,stem="rats") +modelSaveState(stem="rats") +require(coda) +rats.coda <- buildMCMC("alpha0") +stopifnot(length(rats.coda[[1]])==1000) +modelCheck("ratsmodel.txt") +dat <- dget("Ratsdata.txt") +modelData(bugsData(dat)) +modelCompile(numChains=2) +inits <- dget("Ratsinits.txt") +modelInits(bugsInits(list(inits,inits), numChains=2)) +# writeModel() # tested in help page example + +## Manuals +if (interactive()) help.BRugs() # todo remove link from doc +if (interactive()) help.WinBUGS() + +## Gen inits +modelCheck("ratsmodel.txt") +modelData("ratsdata.txt") +modelCompile(numChains=2) +inits <- dget("Ratsinits.txt"); inits[c("alpha","beta")] <- NULL +modelInits(bugsInits(list(inits,inits), numChains=2)) +modelGenInits() + +## Functions to tune updaters. Just make sure their interfaces are correct +#modelSetAP() +#modelSetIts() +#modelSetOR() +#modelEnable() +#modelDisable() + +## Info functions +stopifnot(infoNodeMethods("alpha")[,"Type"] == "UpdaterNormal.StdUpdater") +stopifnot(infoNodeTypes("alpha")[1,"Type"]=="GraphNormal.StdNode") +stopifnot(infoUpdatersbyName()["alpha.c","Type"]=="conjugatenormalupdater") +stopifnot(infoUpdatersbyDepth()["alpha.c","Type"]=="conjugatenormalupdater") +mem <- infoMemory() +stopifnot(is.numeric(mem) && mem > 0) +stopifnot(any(infoModules()[,"Module"] == "Kernel")) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-17 17:38:38
|
Revision: 156 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=156&view=rev Author: chris-jackson Date: 2010-05-17 17:38:32 +0000 (Mon, 17 May 2010) Log Message: ----------- Give error if scalar node supplied to setValues(), and return invisibly. Modified Paths: -------------- trunk/BRugs/R/set.values.R Modified: trunk/BRugs/R/set.values.R =================================================================== --- trunk/BRugs/R/set.values.R 2010-05-17 17:36:48 UTC (rev 155) +++ trunk/BRugs/R/set.values.R 2010-05-17 17:38:32 UTC (rev 156) @@ -8,6 +8,8 @@ # if(any(DoNotSetNA)) # warning("Some NA values formerly had a non-NA value -- left unchanged") # values[DoNotSetNA] <- cv[DoNotSetNA] + if (dimensions(nodeLabel) == 0) + stop("Only allowed for vector, not scalar nodes") command <- "BugsRobjects.SetVariable" .C("CharArray", command, nchar(command), nodeLabel, nchar(nodeLabel), integer(1), PACKAGE="BRugs") command <- "BugsRobjects.GetSize" @@ -17,6 +19,8 @@ if(length(values) != nodeSize) stop("length(values) does not correspond to the node size") command <- "BugsRobjects.SetValues" - .C("RealArray", command, nchar(command), as.double(values), as.integer(nodeSize), - integer(1), NAOK = TRUE, PACKAGE="BRugs") + res <- .C("RealArray", command, nchar(command), as.double(values), as.integer(nodeSize), + integer(1), NAOK = TRUE, PACKAGE="BRugs") + handleRes(res[[5]]) + invisible() } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-17 17:36:54
|
Revision: 155 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=155&view=rev Author: chris-jackson Date: 2010-05-17 17:36:48 +0000 (Mon, 17 May 2010) Log Message: ----------- Better error handling. Don't try to run bugsInits() on the name of a non-existent file, and then generate initial values if none have been supplied. Modified Paths: -------------- trunk/BRugs/R/BRugsFit.R Modified: trunk/BRugs/R/BRugsFit.R =================================================================== --- trunk/BRugs/R/BRugsFit.R 2010-05-17 13:28:37 UTC (rev 154) +++ trunk/BRugs/R/BRugsFit.R 2010-05-17 17:36:48 UTC (rev 155) @@ -4,7 +4,7 @@ DIC = TRUE, working.directory = NULL, digits = 5, seed=NULL, BRugsVerbose = getOption("BRugsVerbose")){ - if(is.null(BRugsVerbose)) + if(is.null(BRugsVerbose)) BRugsVerbose <- TRUE op <- options("BRugsVerbose" = BRugsVerbose) on.exit(options(op)) @@ -19,21 +19,22 @@ if(!is.R()) on.exit(file.remove(modelFile), add = TRUE) } if(!file.exists(modelFile)) stop(modelFile, " does not exist") - if(file.info(modelFile)$isdir) stop(modelFile, " is a directory, but a file is required") + if(file.info(modelFile)$isdir) stop(modelFile, " is a directory, but a file is required") modelCheck(modelFile) if(!(is.vector(data) && is.character(data) && all(file.exists(data)))) - data <- bugsData(data, digits = digits) - modelData(data) + data <- bugsData(data, digits = digits) + modelData(data) modelCompile(numChains) - if(!is.null(seed)) modelSetSeed(newSeed=seed) - if(missing(inits)){ - modelGenInits() - } else { - if(is.list(inits) || is.function(inits) || (is.character(inits) && !any(file.exists(inits)))) - inits <- bugsInits(inits = inits, numChains = numChains, digits = digits) - if(BRugsVerbose) print(inits) - modelInits(inits) + if(!is.null(seed)) modelSetSeed(seed) + if(!missing(inits)){ + if(is.list(inits) || is.function(inits)) + inits <- bugsInits(inits = inits, numChains = numChains, digits = digits) + if (is.character(inits) && any(file.exists(inits))){ + if(BRugsVerbose) print(inits) + modelInits(inits) + } } + modelGenInits() samplesSetThin(nThin) modelUpdate(nBurnin) if(DIC){ @@ -44,6 +45,6 @@ modelUpdate(nIter) if(coda) return(buildMCMC("*")) - else + else return(list(Stats = samplesStats("*"), DIC = if(DIC) dicStats())) } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-17 13:28:44
|
Revision: 154 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=154&view=rev Author: chris-jackson Date: 2010-05-17 13:28:37 +0000 (Mon, 17 May 2010) Log Message: ----------- New facility to show memory allocated to OpenBUGS Added Paths: ----------- trunk/BRugs/R/model.allocatedMemory.R trunk/BRugs/man/model.allocatedMemory.Rd Added: trunk/BRugs/R/model.allocatedMemory.R =================================================================== --- trunk/BRugs/R/model.allocatedMemory.R (rev 0) +++ trunk/BRugs/R/model.allocatedMemory.R 2010-05-17 13:28:37 UTC (rev 154) @@ -0,0 +1,9 @@ +"modelAllocatedMemory" <- + function(){ + command <- "BugsEmbed.AllocatedMemory" + res <- .CmdInterpreter(command) + buffer <- file.path(tempdir(), "buffer.txt") + res <- readLines(buffer) + mem <- as.numeric(gsub("^([0-9]+).+", "\\1", res)) + mem + } Added: trunk/BRugs/man/model.allocatedMemory.Rd =================================================================== --- trunk/BRugs/man/model.allocatedMemory.Rd (rev 0) +++ trunk/BRugs/man/model.allocatedMemory.Rd 2010-05-17 13:28:37 UTC (rev 154) @@ -0,0 +1,13 @@ +\name{modelAllocatedMemory} +\alias{modelAllocatedMemory} +\title{Show memory usage} +\description{Shows the amount of memory allocated to OpenBUGS} +\usage{ +modelAllocatedMemory() +} +\value{ + Amount of memory allocated to OpenBUGS, in bytes. +} +\seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}} +\keyword{interface} + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-17 13:20:15
|
Revision: 153 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=153&view=rev Author: chris-jackson Date: 2010-05-17 13:20:09 +0000 (Mon, 17 May 2010) Log Message: ----------- Removed modelEnableDynamic and modelDisableDynamic which implemented an OpenBUGS procedure which doesn't exist any more. Note that a "compile logicals" facility exists now, but this only works in the OpenBUGS GUI. Removed Paths: ------------- trunk/BRugs/R/model.dynamic.R trunk/BRugs/man/model.dynamic.Rd Deleted: trunk/BRugs/R/model.dynamic.R =================================================================== --- trunk/BRugs/R/model.dynamic.R 2010-05-17 12:58:16 UTC (rev 152) +++ trunk/BRugs/R/model.dynamic.R 2010-05-17 13:20:09 UTC (rev 153) @@ -1,15 +0,0 @@ -"modelEnableDynamic" <- -function() -# Enable Dynamic Compilation -{ - command <- "BugsEmbed.CompiledGuard; BugsEmbed.EnableDynamic" - invisible(.CmdInterpreter(command)[[3]]) -} - -"modelDisableDynamic" <- -function() -# Disable Dynamic Compilation -{ - command <- "BugsEmbed.CompiledGuard; BugsEmbed.DisableDynamic" - invisible(.CmdInterpreter(command)[[3]]) -} Deleted: trunk/BRugs/man/model.dynamic.Rd =================================================================== --- trunk/BRugs/man/model.dynamic.Rd 2010-05-17 12:58:16 UTC (rev 152) +++ trunk/BRugs/man/model.dynamic.Rd 2010-05-17 13:20:09 UTC (rev 153) @@ -1,12 +0,0 @@ -\name{modelDynamic} -\alias{modelEnableDynamic} -\alias{modelDisableDynamic} -\title{Controlling Dynamic Compilation} -\description{These functions are used to enable and disable the feature for dynamic compilation.} -\usage{ -modelEnableDynamic() -modelDisableDynamic() -} -\seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}} -\keyword{interface} - This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-17 12:58:22
|
Revision: 152 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=152&view=rev Author: chris-jackson Date: 2010-05-17 12:58:16 +0000 (Mon, 17 May 2010) Log Message: ----------- minor tidying Modified Paths: -------------- trunk/BRugs/man/bugs.inits.Rd Modified: trunk/BRugs/man/bugs.inits.Rd =================================================================== --- trunk/BRugs/man/bugs.inits.Rd 2010-05-17 12:55:13 UTC (rev 151) +++ trunk/BRugs/man/bugs.inits.Rd 2010-05-17 12:58:16 UTC (rev 152) @@ -1,13 +1,13 @@ \name{bugsInits} \alias{bugsInits} \title{Writing input for OpenBUGS} -\description{Write files containing inits.} +\description{Write files containing initial values.} \usage{ bugsInits(inits, numChains = 1, fileName, digits = 5) } \arguments{ \item{inits}{a list with \code{n.chains} elements; each element of the list is - itself a list of starting values for the OpenBUGS model, \emph{or} + itself a list of starting values for the OpenBUGS model, \emph{or} a function creating (possibly random) initial values} \item{numChains}{number of Markov chains} \item{fileName}{the filename(s), one for each chain. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-17 12:55:24
|
Revision: 151 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=151&view=rev Author: chris-jackson Date: 2010-05-17 12:55:13 +0000 (Mon, 17 May 2010) Log Message: ----------- Documented that setValues only works for vector, not scalar nodes. This is a limitation of the underlying OpenBUGS procedure BugsRobjects.SetValues Modified Paths: -------------- trunk/BRugs/man/set.values.Rd Modified: trunk/BRugs/man/set.values.Rd =================================================================== --- trunk/BRugs/man/set.values.Rd 2010-05-17 12:52:12 UTC (rev 150) +++ trunk/BRugs/man/set.values.Rd 2010-05-17 12:55:13 UTC (rev 151) @@ -1,12 +1,13 @@ \name{setValues} \alias{setValues} \title{Setting current values} -\description{This function sets current values for a variable for future iterations.} +\description{This function sets the current values of a variable for future + iterations. Only supported for vector, not scalar nodes.} \usage{ setValues(nodeLabel, values) } \arguments{ - \item{nodeLabel}{Character vector of length 1, name of a variable in the model.} + \item{nodeLabel}{Character vector of length 1, name of a vector node in the model.} \item{values}{The values to be set, generated, e.g., by \code{\link{currentValues}}.} } \details{ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-17 12:52:18
|
Revision: 150 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=150&view=rev Author: chris-jackson Date: 2010-05-17 12:52:12 +0000 (Mon, 17 May 2010) Log Message: ----------- "plot=TRUE/FALSE" option added to density plots. Modified Paths: -------------- trunk/BRugs/R/plot.density.R trunk/BRugs/R/samples.density.R trunk/BRugs/man/plot.density.Rd trunk/BRugs/man/samples.density.Rd Modified: trunk/BRugs/R/plot.density.R =================================================================== --- trunk/BRugs/R/plot.density.R 2010-05-17 12:48:48 UTC (rev 149) +++ trunk/BRugs/R/plot.density.R 2010-05-17 12:52:12 UTC (rev 150) @@ -1,5 +1,5 @@ "plotDensity" <- -function(node, main = NULL, xlab = "" , ylab = "", col = "red", ...) +function(node, plot=TRUE, main = NULL, xlab = "" , ylab = "", col = "red", ...) # Plot posterior density for single component of OpenBUGS name { sM <- samplesMonitors(node) @@ -8,7 +8,7 @@ nodeName <- sQuote(node) sampleSize <- samplesSize(node) sample <- samplesSample(node) - + absSample <- abs(sample) intSample <- as.integer(absSample + 1.0E-10) zero <- absSample - intSample @@ -18,15 +18,20 @@ d <- density(sample, adjust = 1.25) else d <- density(sample) - plot(d$x, d$y, type = "l", main = if(is.null(main)) nodeName else main, - xlab = xlab , ylab = ylab, col = col, ...) + if (plot) + plot(d$x, d$y, type = "l", main = if(is.null(main)) nodeName else main, + xlab = xlab , ylab = ylab, col = col, ...) + res <- d } else{ histogram <- table(intSample) / sampleSize xRange <- range(intSample) xLim <- c(xRange[1] - 0.5, xRange[2] + 0.5) - plot(histogram, type = "h", xlim = xLim, ylim = c(0, 1), - main = if(is.null(main)) nodeName else main, - xlab = xlab , ylab = ylab, col = col, ...) + if (plot) + plot(histogram, type = "h", xlim = xLim, ylim = c(0, 1), + main = if(is.null(main)) nodeName else main, + xlab = xlab , ylab = ylab, col = col, ...) + res <- histogram } + if (plot) invisible(res) else return(res) } Modified: trunk/BRugs/R/samples.density.R =================================================================== --- trunk/BRugs/R/samples.density.R 2010-05-17 12:48:48 UTC (rev 149) +++ trunk/BRugs/R/samples.density.R 2010-05-17 12:52:12 UTC (rev 150) @@ -1,8 +1,9 @@ "samplesDensity" <- -function(node, beg = samplesGetBeg(), end = samplesGetEnd(), -firstChain = samplesGetFirstChain(), lastChain = samplesGetLastChain(), -thin = samplesGetThin(), mfrow = c(3, 2), ask = NULL, ann = TRUE, ...) -# Plot posterior density +function(node, beg = samplesGetBeg(), end = samplesGetEnd(), +firstChain = samplesGetFirstChain(), lastChain = samplesGetLastChain(), +thin = samplesGetThin(), plot = TRUE, mfrow = c(3, 2), ask = NULL, +ann = TRUE, ...) +# Plot posterior density { if(is.null(ask)) { if (is.R()) @@ -15,7 +16,7 @@ oldFirstChain <- samplesGetFirstChain() oldLastChain <- samplesGetLastChain() oldThin <- samplesGetThin() - on.exit({ + on.exit({ samplesSetBeg(oldBeg) samplesSetEnd(oldEnd) samplesSetFirstChain(oldFirstChain) @@ -34,7 +35,11 @@ par(mfrow = mfrow, ask = ask, ann = ann) else par(mfrow = mfrow, ask = ask) - junk <- sapply(mons, plotDensity, ...) + result <- sapply(mons, plotDensity, plot=plot, ...) if (!is.R()) invisible() + else { + if(plot) invisible(result) + else return(result) + } } Modified: trunk/BRugs/man/plot.density.Rd =================================================================== --- trunk/BRugs/man/plot.density.Rd 2010-05-17 12:48:48 UTC (rev 149) +++ trunk/BRugs/man/plot.density.Rd 2010-05-17 12:52:12 UTC (rev 150) @@ -1,15 +1,18 @@ \name{plotDensity} \alias{plotDensity} \title{Plot density estimate or histogram of a scalar variable} -\description{This function plots a smoothed kernel density estimate for a scalar variable if it is continuous +\description{This function plots a smoothed kernel density estimate for a scalar variable if it is continuous or a histogram if it is discrete.} \usage{ -plotDensity(node, main = NULL, xlab = "" , ylab = "", col = "red", ...) +plotDensity(node, plot=TRUE, main = NULL, xlab = "" , ylab = "", col = "red", + ...) } \arguments{ \item{node}{Character, name of a scalar variable in the model.} - \item{main, xlab, ylab, col}{graphical parameters, see \code{\link{plot.default}}} - \item{...}{Further graphical parameters as in \code{\link{par}}.} + \item{plot}{Logical, whether to plot the trace or only return density estimates. + If \code{TRUE}, density estimates are returned invisibly.} + \item{main, xlab, ylab, col}{graphical parameters, see \code{\link{plot.default}}} + \item{...}{Further graphical parameters as in \code{\link{par}}.} } \details{Acts on a scalar variable. See the wrapper function \code{\link{samplesDensity}} for more details.} \seealso{\code{\link{samplesDensity}}, \code{\link{BRugs}}, \code{\link{help.WinBUGS}}} Modified: trunk/BRugs/man/samples.density.Rd =================================================================== --- trunk/BRugs/man/samples.density.Rd 2010-05-17 12:48:48 UTC (rev 149) +++ trunk/BRugs/man/samples.density.Rd 2010-05-17 12:52:12 UTC (rev 150) @@ -1,31 +1,33 @@ \name{samplesDensity} \alias{samplesDensity} \title{Plot density estimate or histogram} -\description{This function plots a smoothed kernel density estimate for a variable if it is continuous +\description{This function plots a smoothed kernel density estimate for a variable if it is continuous or a histogram if it is discrete.} \usage{ -samplesDensity(node, beg = samplesGetBeg(), end = samplesGetEnd(), - firstChain = samplesGetFirstChain(), +samplesDensity(node, beg = samplesGetBeg(), end = samplesGetEnd(), + firstChain = samplesGetFirstChain(), lastChain = samplesGetLastChain(), thin = samplesGetThin(), - mfrow = c(3, 2), ask = NULL, ann = TRUE, ...) + plot = TRUE, mfrow = c(3, 2), ask = NULL, ann = TRUE, ...) } \arguments{ \item{node}{Character vector of length 1, name of a variable in the model.} \item{beg, end}{Arguments to select a slice of monitored values corresponding to iterations \code{beg:end}.} \item{firstChain, lastChain}{Arguments to select a sub group of chains to plot density estimate or histogram for.} \item{thin}{to only use every \code{thin}-th value of the stored sample for statistics.} + \item{plot}{Logical, whether to plot the trace or only return density estimates. + If \code{TRUE}, density estimates are returned invisibly.} \item{mfrow, ask, ann}{Graphical parameters, see \code{\link{par}} for details. \code{ask} defaults to \code{TRUE} unless it is plotting into an already opened non-interactive device. The \code{ann} parameter is not available in S-PLUS, and will be ignored if it is set.} \item{...}{Further graphical parameters as in \code{\link{par}} may also be passed as arguments to \code{\link{plotDensity}}.} } -\details{If the variable of interest is an array, slices of the array can be selected using the notation - \code{variable[lower0:upper0, lower1:upper1, ...]}. +\details{If the variable of interest is an array, slices of the array can be selected using the notation + \code{variable[lower0:upper0, lower1:upper1, ...]}. A star \sQuote{\code{*}} can be entered as shorthand for all the stored samples. - + If the arguments are left at their defaults the whole sample for all chains will be used for calculation.} -\note{If the MCMC simulation has an adaptive phase it will not be possible to make inference using values +\note{If the MCMC simulation has an adaptive phase it will not be possible to make inference using values sampled before the end of this phase.} \seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}} \keyword{interface} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-17 12:48:57
|
Revision: 149 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=149&view=rev Author: chris-jackson Date: 2010-05-17 12:48:48 +0000 (Mon, 17 May 2010) Log Message: ----------- Mechanism for setting the random number seed has changed since OpenBUGS 3.0.3. Now you can only supply an integer from 1 to 14 defining the "state" of the random number generator. Copied the relevant documentation from the OpenBUGS manual, though there's hardly any documentation on the actual algorithms used by the generator. Modified Paths: -------------- trunk/BRugs/R/model.get.seed.R trunk/BRugs/R/model.set.seed.R trunk/BRugs/man/model.seed.Rd Modified: trunk/BRugs/R/model.get.seed.R =================================================================== --- trunk/BRugs/R/model.get.seed.R 2010-05-17 12:45:24 UTC (rev 148) +++ trunk/BRugs/R/model.get.seed.R 2010-05-17 12:48:48 UTC (rev 149) @@ -1,11 +1,7 @@ "modelGetSeed" <- -function(i = 1) +function() # Get the seed of random number generator { - if(!is.numeric(i)) - stop("i ", "must be numeric") - command <- paste("BugsEmbed.index := ", as.integer(i), ";BugsEmbed.GetRNState") - res <- .CmdInterpreter(command)[[3]] - if(res) stop("Getting seed returned with an error.") - buffer() + command <- "BugsEmbed.preSet" + .Integer(command) } Modified: trunk/BRugs/R/model.set.seed.R =================================================================== --- trunk/BRugs/R/model.set.seed.R 2010-05-17 12:45:24 UTC (rev 148) +++ trunk/BRugs/R/model.set.seed.R 2010-05-17 12:48:48 UTC (rev 149) @@ -1,18 +1,14 @@ -"modelSetSeed" <- -function(newSeed) +"modelSetSeed" <- +function(state) # Set the seed of random number generator { - if(!is.numeric(newSeed)) - stop("newSeed ", "must be numeric") - newSeed <- as.integer(newSeed) - for(i in seq(along=newSeed)){ - command <- paste("BugsEmbed.index :=", i, - ";BugsEmbed.SetRNGuard; BugsEmbed.SetRNState(", newSeed[i], ")" ) - res <- .CmdInterpreter(command)[[3]] - } + if(!state %in% 1:14) + stop("state must be an integer from 1 to 14") + newSeed <- as.integer(state) + command <- paste("BugsEmbed.SetRNGuard; BugsEmbed.SetRNState(", state, ")" ) + res <- .CmdInterpreter(command)[[3]] if(!res){ if(getOption("BRugsVerbose")) - message("Seed successfully set") - }else stop("Setting seed returned with an error.") - -} + message("Random number generator state successfully set") + }else stop("Setting random number generator state returned with an error.") +} Modified: trunk/BRugs/man/model.seed.Rd =================================================================== --- trunk/BRugs/man/model.seed.Rd 2010-05-17 12:45:24 UTC (rev 148) +++ trunk/BRugs/man/model.seed.Rd 2010-05-17 12:48:48 UTC (rev 149) @@ -4,15 +4,17 @@ \title{Seed of Random Number Generator} \description{These functions set/return the seed of the random number generator.} \usage{ -modelSetSeed(newSeed) -modelGetSeed(i = 1) +modelSetSeed(state) +modelGetSeed() } \arguments{ - \item{newSeed}{a positive, non zero (vector of) integer(s). - More than one integer if the chosen random number generator requires more seed components.} - \item{i}{indicates which component of the seed should be returned.} + \item{state}{An integer from 1 to 14. The internal state of the OpenBUGS random number generator can be set to one of 14 predefined states. Each predefined state is \eqn{10^12}{10^12} draws apart to avoid overlap in random number sequences.} } -\details{Warning: \code{modelSetSeed} must not be used before \code{\link{modelCompile}} has been executed successfully!} +\details{Warning: \code{modelSetSeed} must not be used before + \code{\link{modelCompile}} has been executed successfully! + The state can be changed after initial values are generated + but before updates have been performed, however, this is not recommended. +} \seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}} \keyword{interface} \concept{update} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-17 12:45:34
|
Revision: 148 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=148&view=rev Author: chris-jackson Date: 2010-05-17 12:45:24 +0000 (Mon, 17 May 2010) Log Message: ----------- Workaround for problem with vector nodes. samplesSet(alpha[1]) followed by samplesSet(alpha[2]) was giving a meaningless error. The problem is with SamplesEmbed.Labels (called by samplesMonitors()). If a monitor has just been set, but no updates have been made, then SamplesEmbedLabels thinks that the node isn't monitored. This should probably be fixed in OpenBUGS in the long term, but we can work around this for the moment. Modified Paths: -------------- trunk/BRugs/R/samples.set.R Modified: trunk/BRugs/R/samples.set.R =================================================================== --- trunk/BRugs/R/samples.set.R 2010-05-10 15:17:28 UTC (rev 147) +++ trunk/BRugs/R/samples.set.R 2010-05-17 12:45:24 UTC (rev 148) @@ -4,20 +4,21 @@ { nodeName <- sQuote(node) for(i in seq(along=nodeName)){ - sM <- paste(samplesMonitors(node[i]), collapse = " ") + sM <- paste(suppressMessages(samplesMonitors(node[i])), collapse = " ") if(sM == "model must be initialized before monitors used") stop("model must be initialized before monitors used") - if(sM == "inference can not be made when sampler is in adaptive phase") + if(sM %in% c("inference can not be made when sampler is in adaptive phase", + "model has probably not yet been updated")) alreadySet <- FALSE - else + else alreadySet <- !length(grep("no monitor set", sM)) eval(alreadySet) - command <- paste("SamplesEmbed.SetVariable(", nodeName[i], + command <- paste("SamplesEmbed.SetVariable(", nodeName[i], ");SamplesEmbed.SetGuard;SamplesEmbed.Set") .CmdInterpreter(command) buffer <- file.path(tempdir(), "buffer.txt") rlb <- readLines(buffer) - if(rlb == "") + if(rlb == "") message("either model has not been updated or variable ", nodeName[i], " already set") else{ if(getOption("BRugsVerbose")){ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <li...@us...> - 2010-05-10 15:17:34
|
Revision: 147 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=147&view=rev Author: ligges Date: 2010-05-10 15:17:28 +0000 (Mon, 10 May 2010) Log Message: ----------- save files into the right place now and improve docs Modified Paths: -------------- trunk/BRugs/R/model.save.state.R trunk/BRugs/man/model.save.state.Rd Modified: trunk/BRugs/R/model.save.state.R =================================================================== --- trunk/BRugs/R/model.save.state.R 2010-05-10 09:46:10 UTC (rev 146) +++ trunk/BRugs/R/model.save.state.R 2010-05-10 15:17:28 UTC (rev 147) @@ -1,6 +1,10 @@ "modelSaveState" <- function(stem) { -# Saves the sate of each chain in OpenBUGS model +## Saves the sate of each chain in OpenBUGS model + if(!is.character(stem) || length(stem)!=1) + stop("'stem' must be character of length 1") + if(dirname(stem) == ".") + stem <- file.path(getwd(), basename(stem)) command <- paste("BugsEmbed.UpdateGuard", ";BugsEmbed.WriteChains(", sQuote(stem), ")") .CmdInterpreter(command) if(getOption("BRugsVerbose")) Modified: trunk/BRugs/man/model.save.state.Rd =================================================================== --- trunk/BRugs/man/model.save.state.Rd 2010-05-10 09:46:10 UTC (rev 146) +++ trunk/BRugs/man/model.save.state.Rd 2010-05-10 15:17:28 UTC (rev 147) @@ -6,15 +6,20 @@ modelSaveState(stem) } \arguments{ - \item{stem}{?????.} + \item{stem}{The filestem of the files to be generated.} } -\note{This function can be executed once a model has been successfully checked - ????? -(see \code{\link{modelCheck}}). +\details{ + Example for argument \code{stem}: + If \code{stem = "c:/myFolder/stem"}, the resulting files + are called \file{stem1.txt}, ..., \file{stemN.txt}. + They are written into the \code{tempdir()} + and copied to the path \file{"c:/myFolder"}. +} +\note{This function can be executed once a model has been successfully checked (see \code{\link{modelCheck}}). + If an attempt is made to execute this function in an inappropriate context the generic error message \sQuote{command is not allowed (greyed out)} is displayed. - ????? } \seealso{\code{\link{BRugs}}, \code{\link{help.WinBUGS}}} \keyword{interface} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <li...@us...> - 2010-05-10 09:46:16
|
Revision: 146 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=146&view=rev Author: ligges Date: 2010-05-10 09:46:10 +0000 (Mon, 10 May 2010) Log Message: ----------- OpenBUGS 3.1.0 is there .... Modified Paths: -------------- trunk/BRugs/NEWS trunk/BRugs/R/zzz.R Modified: trunk/BRugs/NEWS =================================================================== --- trunk/BRugs/NEWS 2010-05-07 13:13:10 UTC (rev 145) +++ trunk/BRugs/NEWS 2010-05-10 09:46:10 UTC (rev 146) @@ -2,7 +2,7 @@ ===================== Update 0.6-0 -- Switch to new OpenBUGS (currently 3.0.8) +- Switch to new OpenBUGS (currently 3.1.0) - 32-bit versions only Update 0.5-3 @@ -13,5 +13,5 @@ Update 0.5-2 - added seed argument to BRugsFit() - fix writeModel() to work for separatly specified function body -- fix writeModel() to make larger numeric (particularly integer) values +- fix writeModel() to make larger numeric (particularly integer) values in scientific notation work Modified: trunk/BRugs/R/zzz.R =================================================================== --- trunk/BRugs/R/zzz.R 2010-05-07 13:13:10 UTC (rev 145) +++ trunk/BRugs/R/zzz.R 2010-05-10 09:46:10 UTC (rev 146) @@ -15,7 +15,7 @@ } ".onAttach" <- function(lib, pkg){ - message("Welcome to BRugs running on OpenBUGS version 3.0.8") + message("Welcome to BRugs running on OpenBUGS version 3.1.0") } ".onUnload" <- function(libpath){ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2010-05-07 13:13:17
|
Revision: 145 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=145&view=rev Author: chris-jackson Date: 2010-05-07 13:13:10 +0000 (Fri, 07 May 2010) Log Message: ----------- Fix for crash in samplesSize on non-scalar nodes, returns 0 for non-sampled nodes. buildMCMC returns NA instead of crashing for node with no sample Comments corrected in model.setIts.R and model.setOR.R Modified Paths: -------------- trunk/BRugs/R/buildMCMC.R trunk/BRugs/R/model.setIts.R trunk/BRugs/R/model.setOR.R trunk/BRugs/R/samples.size.R Modified: trunk/BRugs/R/buildMCMC.R =================================================================== --- trunk/BRugs/R/buildMCMC.R 2010-05-05 21:43:23 UTC (rev 144) +++ trunk/BRugs/R/buildMCMC.R 2010-05-07 13:13:10 UTC (rev 145) @@ -41,28 +41,32 @@ numChains <- samplesGetLastChain() - samplesGetFirstChain() + 1 sampleSize <- sampleSize %/% numChains beg <- end - sampleSize * thin + 1 - samples <- lapply(mons, subBuildMCMC) - samplesChain <- vector(mode="list", length=numChains) - - for(i in 1:numChains){ - if (is.R()) - temp <- sapply(samples, function(x) x[,i]) - else - temp <- sapply(samples, function(x,j) { x[,j]}, j=i) + if (sampleSize==0) { + mcmcobj <- NA + } + else { + samples <- lapply(mons, subBuildMCMC) + samplesChain <- vector(mode="list", length=numChains) + for(i in 1:numChains){ + if (is.R()) + temp <- sapply(samples, function(x) x[,i]) + else + temp <- sapply(samples, function(x,j) { x[,j]}, j=i) ##### If we want to special-case 1D-mcmc objects: -# if(ncol(temp) == 1){ -# dim(temp) <- NULL -# samplesChain[[i]] <- temp -# } -# else{ - samplesChain[[i]] <- temp - colnames(samplesChain[[i]]) <- mons -# } + # if(ncol(temp) == 1){ + # dim(temp) <- NULL + # samplesChain[[i]] <- temp + # } + # else{ + samplesChain[[i]] <- temp + colnames(samplesChain[[i]]) <- mons + # } + } + mcmcobj <- lapply(samplesChain, mcmc, start = beg, end = end, thin = thin) } - mcmcobj <- lapply(samplesChain, mcmc, start = beg, end = end, thin = thin) if(is.R()) - class(mcmcobj) <- "mcmc.list" + class(mcmcobj) <- "mcmc.list" else - oldClass(mcmcobj) <- "mcmc.list" + oldClass(mcmcobj) <- "mcmc.list" mcmcobj } Modified: trunk/BRugs/R/model.setIts.R =================================================================== --- trunk/BRugs/R/model.setIts.R 2010-05-05 21:43:23 UTC (rev 144) +++ trunk/BRugs/R/model.setIts.R 2010-05-07 13:13:10 UTC (rev 145) @@ -1,6 +1,6 @@ "modelSetIts" <- function(factoryName, iterations) -# Set the length of adaptive phase +# Set maximum number of iterations in iterative algorithms { name <- sQuote(factoryName) command <- paste("UpdaterMethods.SetFactory(", name, Modified: trunk/BRugs/R/model.setOR.R =================================================================== --- trunk/BRugs/R/model.setOR.R 2010-05-05 21:43:23 UTC (rev 144) +++ trunk/BRugs/R/model.setOR.R 2010-05-07 13:13:10 UTC (rev 145) @@ -1,6 +1,6 @@ "modelSetOR" <- function(factoryName, overRelaxation) -# Set the length of adaptive phase +# Set over-relaxed updating { name <- sQuote(factoryName) command <- paste("UpdaterMethods.SetFactory(", name, Modified: trunk/BRugs/R/samples.size.R =================================================================== --- trunk/BRugs/R/samples.size.R 2010-05-05 21:43:23 UTC (rev 144) +++ trunk/BRugs/R/samples.size.R 2010-05-07 13:13:10 UTC (rev 145) @@ -2,6 +2,13 @@ function(node) # Size of stored sample of single component of OpenBUGS name { + sM <- samplesMonitors(node) + # Doesn't distinguish between nodes not in the model and nodes not monitored + # so returns 0 for non-existent nodes + if (any(grep("^no monitor set", sM))) return(0) + if (any(grep("^model has probably not yet been updated", sM))) return(0) + if(length(sM) > 1 || sM != node) + stop("node must be a scalar variable from the model") command <- paste("SamplesEmbed.SetVariable(", shQuote(node), ")") .CmdInterpreter(command) command <- "SamplesEmbed.SampleSize" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <li...@us...> - 2010-05-02 18:46:42
|
Revision: 143 http://bugs-r.svn.sourceforge.net/bugs-r/?rev=143&view=rev Author: ligges Date: 2010-05-02 18:46:36 +0000 (Sun, 02 May 2010) Log Message: ----------- make formatdata aware of the dimension of nodes from the model specification to use c() and structure() where appropriate Modified Paths: -------------- trunk/BRugs/R/formatdata.R Modified: trunk/BRugs/R/formatdata.R =================================================================== --- trunk/BRugs/R/formatdata.R 2010-05-02 18:45:44 UTC (rev 142) +++ trunk/BRugs/R/formatdata.R 2010-05-02 18:46:36 UTC (rev 143) @@ -1,24 +1,28 @@ "formatdata" <- function (datalist){ if (!is.list(datalist) || is.data.frame(datalist)) - stop("argument to formatdata() ", "must be a list") + stop("argument to formatdata() ", "must be a list") n <- length(datalist) datalist.string <- vector(n, mode = "list") + datanames <- names(datalist) for (i in 1:n) { - if (length(datalist[[i]]) == 1) - datalist.string[[i]] <- paste(names(datalist)[i], - "=", as.character(datalist[[i]]), sep = "") - if (is.vector(datalist[[i]]) && length(datalist[[i]]) > 1) - datalist.string[[i]] <- paste(names(datalist)[i], - "=c(", paste(as.character(datalist[[i]]), collapse = ", "), - ")", sep = "") - if (is.array(datalist[[i]])) - datalist.string[[i]] <- paste(names(datalist)[i], - "= structure(.Data= c(", paste(as.character(as.vector(aperm(datalist[[i]]))), - collapse = ", "), "), .Dim=c(", paste(as.character(dim(datalist[[i]])), - collapse = ", "), "))", sep = "") + datalist.string[[i]] <- + switch(as.character(dimensions(datanames[i])), + "0" = paste(names(datalist)[i], + "=", as.character(datalist[[i]]), sep = ""), + "1" = paste(names(datalist)[i], + "=c(", paste(as.character(datalist[[i]]), collapse = ", "), + ")", sep = ""), + paste(names(datalist)[i], + "= structure(.Data= c(", + paste(as.character(as.vector(aperm(datalist[[i]]))), collapse = ", "), + "), .Dim=c(", + paste(as.character(dim(datalist[[i]])), collapse = ", "), + "))", sep = "") + ) } - datalist.tofile <- paste("list(", paste(unlist(datalist.string), - collapse = ", "), ")", sep = "") + datalist.tofile <- paste("list(", + paste(unlist(datalist.string), collapse = ", "), + ")", sep = "") return(datalist.tofile) } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |