-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtest_adaptMCMC.r
103 lines (64 loc) · 2.06 KB
/
test_adaptMCMC.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
## =======================================================
## Project: adaptMCMC
##
## Description: test cases for adaptMCMC package
##
## =======================================================
library(devtools)
package.path = "adaptMCMC/" # path must point to the folder containing the WaMaSim files
## simulate a new package installation
load_all(package.path)
## run R CMD check
check(package.path)
## build(package.path)
## -------------------------------------------------------
## multi variate normal
d <- 5 # number of dimensions
(means <- 2^(1:d -1 ))
## covariance matrix
S <- matrix(0, ncol=d, nrow=d)
diag(S) <- 1:d
S[lower.tri(S)] <- 1:sum(lower.tri(S))
Sigma <- S%*%t(S)
library(mvtnorm)
p.log <- function(x) {
dmvnorm(x, means, Sigma, log=TRUE)
}
p.log.list <- function(x) {
if(x[1]<0) {
return (list(log.density=dmvnorm(x, means, Sigma, log=TRUE), x=x))
} else {
return (list(log.density=dmvnorm(x, means, Sigma, log=TRUE), x=x, extra="positive!"))
}
}
p.log.error <- function(x) {
c(dmvnorm(x, means, Sigma, log=TRUE), 1)
}
## ----------------------
## sampling one chain
n <- 2500
burn.in <- n/2
samp <- MCMC(p.log, n, init=rep(0,d), acc.rate=0.234, adapt=TRUE, showProgressBar=T)
samp <- MCMC.add.samples(samp, 500)
str(samp)
samp <- MCMC(p.log.list, n, init=rep(0,d), acc.rate=0.234, adapt=TRUE, showProgressBar=T)
samp <- MCMC.add.samples(samp, 500)
str(samp)
samp <- MCMC(p.log.error, n, init=rep(0,d), acc.rate=0.234, adapt=TRUE, showProgressBar=T)
means
colMeans(samp$samples[-(1:burn.in),])
Sigma
round(var(samp$samples[-(1:burn.in),]),1)
samp$acceptance.rate
plot(convert.to.coda(samp))
## ----------------------
## sampling parallel
n <- 2500
burn.in <- n/2
samp <- MCMC.parallel(p.log, n, n.chain=3, n.cpu=3, init=rep(0,d),
acc.rate=0.234, adapt=TRUE, packages='mvtnorm')
str(samp)
samp <- MCMC.parallel(p.log.list, n, n.chain=3, n.cpu=3, init=rep(0,d),
acc.rate=0.234, adapt=TRUE, packages='mvtnorm')
str(samp)