-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample.r
101 lines (85 loc) · 1.61 KB
/
sample.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
# METHODS FOR SAMPLING USING MODIFIED GIBBS SAMPLING TRANSITION PROBABILITIES.
# SAMPLE FROM THE DISTRIBUTION FOR THE NEXT STATE WITH MHGS.
# Uses Algorithm 3.
sample_trans_MHGS <- function (i,samp,prob,epsilon=0)
{
j <- samp()
pi <- prob(i)
if (pi>1-epsilon)
{ return(j)
}
pj <- prob(j)
if (pj>1-epsilon)
{ return(j)
}
if (j!=i && pj>=pi)
{ return(j)
}
if (i==j)
{ seen <- i
sum <- pi
}
else
{ seen <- c(i,j)
sum <- pi + pj
}
h <- j
ph <- pj
while (sum<epsilon)
{ k <- samp()
if (! k %in% seen)
{ pk <- prob(k)
if (pk>1-epsilon)
{ return(j)
}
sum <- sum + pk
seen <- c(seen,k)
if (h==i)
{ h <- k
ph <- pk
}
}
}
return (if (runif(1)<(1-pi)/(1-ph)) h else i)
}
# SAMPLE FROM THE DISTRIBUTION OF THE NEXT STATE WITH ITERATED METROPOLIZED GS.
sample_trans_IMGS <- function (i,samp,prob,m)
{
pi <- prob(i)
j <- samp()
pj <- prob(j)
p <- NULL
while (j==i || pj<pi)
{
if (is.null(p))
{ p <- numeric(m)
for (k in 1:m)
{ p[k] = if (k==i) pi else if (k==j) pj else prob(k)
}
o = order(p)
if (i==o[m])
{ t <- trans_1(p,i,o)
return (sample(m,1,prob=t))
}
t <- numeric(m+1)
t[m+1] <- 0
k <- m
while (o[k]!=i)
{ t[k] <- t[k+1] + p[o[k]]
k <- k-1
}
low <- i+1
f <- numeric(m)
f[i] <- 1
}
if (j<low)
{ while (k!=j)
{ t[k] <- t[k+1] + p[o[k]]
f[k-1] = f[k] * (t[k] - p[o[k]]) / (t[k] - p[o[k-1]])
k <- k-1
}
low <- j
}
}
return(j)
}