Anda di halaman 1dari 13

Bahan Ajar Mata Kuliah Bayesian Analysis

Oleh: Widyo Pura Buana


Boleh dikutip dengan menyebutkan sumbernya

Menjalankan OpenBugs Dengan R


Langkahnya:
1. Install Software R
2. Download library:
a. Coda Library
i. https://cran.r-project.org/web/packages/coda/index.html, atau
ii. https://cran.r-project.org/bin/windows/contrib/3.2/coda_0.18-1.zip
b. BRugs library
i. https://cran.r-project.org/web/packages/BRugs/index.html
ii. https://cran.r-project.org/bin/windows/contrib/3.2/BRugs_0.8-6.zip
c. R2Winbugs library
i. https://cran.r-project.org/web/packages/R2WinBUGS/index.html
ii. https://cran.r-project.org/bin/windows/contrib/3.2/R2WinBUGS_2.1-21.zip
3. Install coda lilbrary
4. Install Brugs library atau R2Winbugs library
5. Cara Install library: Jalankan Software R, pilih menu Package > Install package(s) from local zip files…

Menjalankan OpenBugs dengan R (Widyo Pura Buana) -1


Setelah coda library dan BRugs library di Install akan muncul layar seperti diatas

6. Contoh menjalankan kasus Ratmodel dari OpenBugs


a. File> New script b. Akan tampil window kosong untuk menulis script

Menjalankan OpenBugs dengan R (Widyo Pura Buana) -2


c. Ketik script dan simpan

d. Menjalankan Script, pilih script yang


akan dijalankan, klik kanan,
pilih Run line or selection

e. Tampilan Hasil Running, Statistiknya dan Plot

Menjalankan OpenBugs dengan R (Widyo Pura Buana) -3


Menjalankan OpenBugs dengan R (Widyo Pura Buana) -4
Plot Dapat disimpan dalam bentuk jpeg atau pdf

Menjalankan OpenBugs dengan R (Widyo Pura Buana) -5


Script R disimpan dalam file ratBRugsR.R
### Step by step example: ###
library("BRugs") # loading BRugs

## Prepare the example files in a temporary directory


exfiles <- dir(options()$OpenBUGSExamples, pattern="^Rats.*txt$", full.names=TRUE)
ok <- file.copy(exfiles, tempdir())

## Now setting the working directory to the temporary one:


oldwd <- setwd(tempdir())

## some usual steps (like clicking in WinBUGS):


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
modelUpdate(1000) # burn in
samplesSet(c("alpha0", "alpha")) # alpha0 and alpha should be monitored
modelUpdate(1000) # 1000 more iterations ....

samplesStats("*") # the summarized results

## some plots
samplesHistory("*", mfrow = c(4, 2)) # plot the chain,
samplesDensity("alpha") # plot the densities,
samplesBgr("alpha[1:6]") # plot the bgr statistics, and
samplesAutoC("alpha[1:6]", 1) # plot autocorrelations of 1st chain

## switch back to the previous working directory:


setwd(oldwd)

## Not run:
# Getting more (online-)help:
if (is.R())
help.BRugs()

## End(Not run)
OUTPUT LENGKAP:
> ### Step by step example: ###
> library("BRugs") # loading BRugs
Welcome to BRugs connected to OpenBUGS version 3.2.3

Menjalankan OpenBugs dengan R (Widyo Pura Buana) -6


Warning message:
package ‘BRugs’ was built under R version 3.2.4
>
> ## Prepare the example files in a temporary directory
> exfiles <- dir(options()$OpenBUGSExamples, pattern="^Rats.*txt$", full.names=TRUE)
> ok <- file.copy(exfiles, tempdir())
>
> ## Now setting the working directory to the temporary one:
> oldwd <- setwd(tempdir())
>
> ## some usual steps (like clicking in WinBUGS):
> modelCheck("Ratsmodel.txt") # check model file
model is syntactically correct
> modelData("Ratsdata.txt") # read data file
data loaded
> modelCompile(numChains=2) # compile model with 2 chains
model compiled
> modelInits(rep("Ratsinits.txt", 2)) # read init data file
Initializing chain 1:
initial values loaded and chain initialized but another chain contain uninitialized
variables
Initializing chain 2:
model is initialized
> modelUpdate(1000) # burn in
1000 updates took 0 s
> samplesSet(c("alpha0", "alpha")) # alpha0 and alpha should be monitored
monitor set for variable 'alpha0'
monitor set for variable 'alpha'
> modelUpdate(1000) # 1000 more iterations ....
1000 updates took 0 s
>
> samplesStats("*") # the summarized results
mean sd MC_error val2.5pc median val97.5pc start sample
alpha[1] 240.0 2.677 0.06440 234.70 240.0 245.1 1001 2000
alpha[2] 247.8 2.687 0.06130 242.60 247.8 253.0 1001 2000
alpha[3] 252.5 2.693 0.05603 247.10 252.5 257.8 1001 2000
alpha[4] 232.6 2.674 0.06223 227.30 232.5 237.9 1001 2000
alpha[5] 231.7 2.689 0.05273 226.40 231.7 237.1 1001 2000
alpha[6] 249.7 2.696 0.06721 244.50 249.7 255.2 1001 2000
alpha[7] 228.8 2.752 0.06149 223.50 228.8 234.3 1001 2000
alpha[8] 248.5 2.590 0.07058 243.60 248.4 253.8 1001 2000
alpha[9] 283.3 2.723 0.06230 278.00 283.3 288.8 1001 2000
alpha[10] 219.3 2.810 0.06349 213.70 219.4 224.7 1001 2000
alpha[11] 258.2 2.730 0.06543 252.90 258.2 263.8 1001 2000
alpha[12] 228.2 2.662 0.06210 223.00 228.2 233.2 1001 2000
alpha[13] 242.4 2.744 0.05407 236.90 242.5 247.8 1001 2000
alpha[14] 268.3 2.713 0.06665 263.00 268.3 273.4 1001 2000
alpha[15] 242.7 2.706 0.06235 237.60 242.7 248.0 1001 2000
alpha[16] 245.3 2.686 0.07050 240.00 245.3 250.6 1001 2000
alpha[17] 232.1 2.657 0.05341 227.10 232.1 237.2 1001 2000
alpha[18] 240.5 2.641 0.04912 235.30 240.5 245.8 1001 2000
alpha[19] 253.7 2.645 0.07569 248.60 253.7 259.0 1001 2000
alpha[20] 241.6 2.747 0.05592 236.10 241.7 246.9 1001 2000
alpha[21] 248.6 2.732 0.06780 243.00 248.6 253.9 1001 2000
alpha[22] 225.2 2.702 0.05999 219.90 225.2 230.6 1001 2000
alpha[23] 228.5 2.766 0.05426 222.90 228.5 233.8 1001 2000
alpha[24] 245.2 2.705 0.05834 240.00 245.2 250.6 1001 2000
alpha[25] 234.4 2.759 0.06141 228.80 234.4 239.9 1001 2000
alpha[26] 253.9 2.721 0.06172 248.50 253.9 259.5 1001 2000
alpha[27] 254.4 2.769 0.05842 249.00 254.4 259.7 1001 2000
alpha[28] 243.0 2.703 0.05809 237.60 243.0 248.4 1001 2000
alpha[29] 217.8 2.755 0.06136 212.30 217.9 223.1 1001 2000
alpha[30] 241.4 2.696 0.06310 236.00 241.4 246.7 1001 2000
alpha0 106.5 3.688 0.07985 99.22 106.5 113.7 1001 2000
>
> ## some plots
> samplesHistory("*", mfrow = c(4, 2)) # plot the chain,
Waiting to confirm page change...
Waiting to confirm page change...
Waiting to confirm page change...
Waiting to confirm page change...

Menjalankan OpenBugs dengan R (Widyo Pura Buana) -7


> samplesDensity("alpha") # plot the densities,
Waiting to confirm page change...
Error in plot.new() : invalid graphics state
> samplesBgr("alpha[1:6]") # plot the bgr statistics, and
> samplesAutoC("alpha[1:6]", 1) # plot autocorrelations of 1st chain
>
> ## switch back to the previous working directory:
> setwd(oldwd)
>
> ## Not run:
> # Getting more (online-)help:
> if (is.R())
+ help.BRugs()
If nothing happens, you should open `C:\Program
Files\OpenBUGS\OpenBUGS323\Manuals\Contents.html' yourself

Letak Data yang digunakan untuk contoh adalah file yang berada di program OPENBUGS

Menjalankan OpenBugs dengan R (Widyo Pura Buana) -8


File yang dijalankan dalam script ada 3 file:
1. Ratsmodel.txt
model
{
for( i in 1 : N ) {
for( j in 1 : T ) {
Y[i , j] ~ dnorm(mu[i , j],tau.c)
mu[i , j] <- alpha[i] + beta[i] * (x[j] - xbar)
}
alpha[i] ~ dnorm(alpha.c,alpha.tau)
beta[i] ~ dnorm(beta.c,beta.tau)
}
tau.c ~ dgamma(0.001,0.001)
sigma <- 1 / sqrt(tau.c)
alpha.c ~ dnorm(0.0,1.0E-6)
alpha.tau ~ dgamma(0.001,0.001)
beta.c ~ dnorm(0.0,1.0E-6)
beta.tau ~ dgamma(0.001,0.001)
alpha0 <- alpha.c - xbar * beta.c
}
2. Ratsdata.txt
list(x = c(8.0, 15.0, 22.0, 29.0, 36.0), xbar = 22, N = 30, T = 5,
Y = structure(
.Data = c(151, 199, 246, 283, 320,
145, 199, 249, 293, 354,
147, 214, 263, 312, 328,
155, 200, 237, 272, 297,
135, 188, 230, 280, 323,
159, 210, 252, 298, 331,
141, 189, 231, 275, 305,
159, 201, 248, 297, 338,
177, 236, 285, 350, 376,
134, 182, 220, 260, 296,
160, 208, 261, 313, 352,
143, 188, 220, 273, 314,
154, 200, 244, 289, 325,
171, 221, 270, 326, 358,
163, 216, 242, 281, 312,
160, 207, 248, 288, 324,
142, 187, 234, 280, 316,
156, 203, 243, 283, 317,
157, 212, 259, 307, 336,
152, 203, 246, 286, 321,
154, 205, 253, 298, 334,
139, 190, 225, 267, 302,
146, 191, 229, 272, 302,
157, 211, 250, 285, 323,
132, 185, 237, 286, 331,
160, 207, 257, 303, 345,
169, 216, 261, 295, 333,
157, 205, 248, 289, 316,
137, 180, 219, 258, 291,
153, 200, 244, 286, 324),
.Dim = c(30,5)))
3. Ratsinits.txt
list(alpha = c( 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250),
beta = c(6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6),
alpha.c = 150, beta.c = 10,
tau.c = 1, alpha.tau = 1, beta.tau = 1)

Sumber BAHAN YANG DIGUNAKAN

Menjalankan OpenBugs dengan R (Widyo Pura Buana) -9


https://theoreticalecology.wordpress.com/setting-up-openbugs-and-r/

Menjalankan OpenBugs dengan R (Widyo Pura Buana) - 10


Plot Yang disimpan sebagai pdf file:

Menjalankan OpenBugs dengan R (Widyo Pura Buana) - 11


Sumber BAHAN YANG DIGUNAKAN

Running WinBugs and OpenBugs from R


http://www.stat.columbia.edu/~gelman/bugsR/runningbugs.html

The software on this page gets updated. Refresh to get latest versions. Last update: 24 Jan 2007.

Setting up R, WinBUGS, and OpenBUGS

To run WinBugs from R

 Write a Bugs model in a file with a .bug extension (in your R working directory; for example,
c:/bayes/)).
 Prepare the inputs to the "bugs" function and run it (see example below).
 A WinBugs14 window will pop up and R will freeze up. The model will now run in WinBugs. It
might take awhile. You will see things happening in the Log window within WinBugs14. When
WinBugs is done, its window will close and R will work again.
 If an error message appears, re-run with the debug=TRUE option. Then, when the model stops
running, the Bugs window will stay open and you can play with the model directly in WinBugs.
When you are ready, you can then close the WinBugs14 window and R will resume.
 To see the inferences, use the "print" and "plot" functions (see example below).
 To work with the simulations, use the "attach.all" function (see example below).
 For more information, type "help(bugs)" when in R.

To run OpenBugs from R

 Exactly the same steps as above, except that you add program="openbugs" to the call to bugs()
from R (see end of the example below)
 Also the debug=TRUE option is not yet set up when you call OpenBUGS.

Menjalankan OpenBugs dengan R (Widyo Pura Buana) - 12


Example

 8 schools analysis from Section 5.5 of "Bayesian Data Analysis"


 Put the following in the file "schools.bug" in your R working directory (it is convenient to edit this
and other .bug and .R files in XEmacs):
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)
}
 Save this file as "schools.dat" in your R working directory.
 Do the following commands in R:
schools <- read.table ("schools.dat", header=TRUE)
J <- nrow(schools)
y <- schools$estimate
sigma.y <- schools$sd
data <- list ("J", "y", "sigma.y")
inits <- function() {list (theta=rnorm(J,0,100), mu.theta=rnorm(1,0,100),
sigma.theta=runif(1,0,100))}
parameters <- c("theta", "mu.theta", "sigma.theta")
schools.sim <- bugs (data, inits, parameters, "schools.bug", n.chains=3, n.iter=1000)
 The WinBugs14 window will open, run the script (this will take a few seconds, and you'll see stuff
happening in the Log window in WinBugs14), close itself, and return to R.
 Do the following commands in R:
print (schools.sim)
plot (schools.sim)
 You will see this on the R console and this in the graphics window. (For an example of a model
with more parameters, see here and here.)
 The printed output for this example is schools.sim$summary: summaries of the parameter
inferences and convergence monitoring.
 Do the following command in R:
attach.bugs (schools.sim)
 The simulated parameter values are now saved in R as:
"theta": a 1500 x 8 matrix, representing 1500 simulations of the vector theta
"mu.theta": a vector of length 1500 of simulations of mu.theta
"sigma.theta": a vector of length 1500 of simulations of sigma.theta.
 For more information, type "help(bugs)" when in R.
 To fit using OpenBUGS:
library ("BRugs")
schools.sim <- bugs (data, inits, parameters, "schools.bug", n.chains=3, n.iter=1000,
program="openbugs")

Back to Andrew Gelman's homepage.

Menjalankan OpenBugs dengan R (Widyo Pura Buana) - 13

Anda mungkin juga menyukai