File: mcmc.R

package info (click to toggle)
r-cran-coda 0.13-2-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 456 kB
  • sloc: makefile: 2
file content (317 lines) | stat: -rw-r--r-- 7,972 bytes parent folder | download | duplicates (2)
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"[.mcmc" <- function (x, i, j, drop = missing(i)) 
{
  ## In S-PLUS the code is altered so that the user can
  ## pick out particular parameters by calling mcmc.obj[,c("param1", "param2")]
  xstart <- start(x)
  xthin <- thin(x)
  if (is.R()) {
    y <- NextMethod("[")
  }
  else {
    y <- as.matrix(x)[i,j]
  }
  if (length(y) == 0 || is.null(y)) 
    return(y)
  if (missing(i)) 
    return(mcmc(y, start = xstart, thin = xthin))
  else
    return(y)
}

"as.mcmc" <- function (x) 
  UseMethod("as.mcmc")

"as.mcmc.default" <- function (x) 
  if (is.mcmc(x)) x else mcmc(x)

"as.ts.mcmc" <- function (x, ...) 
{
  x <- as.mcmc(x)
  y <- ts(x, start = start(x), end = end(x), deltat = thin(x))
  attr(y, "mcpar") <- NULL
  return(y)
}

"start.mcmc" <- function (x, ...) 
{
  mcpar(as.mcmc(x))[1]
}

"end.mcmc" <- function (x, ...) 
{
  mcpar(as.mcmc(x))[2]
}

"frequency.mcmc" <- function (x, ...) 
{
  1/thin.mcmc(x)
}

"thin.mcmc" <- function (x, ...) 
{
  mcpar(as.mcmc(x))[3]
}

"is.mcmc" <- function (x) 
{
  if (inherits(x, "mcmc")) 
    if (length(dim(x)) == 3) 
      stop("Obsolete mcmc object\nUpdate with a command like\nx <- mcmcUpgrade(x)")
    else TRUE
  else FALSE
}

"mcmc" <- function (data = NA, start = 1, end = numeric(0), thin = 1) 
{
  if (is.matrix(data)) {
    niter <- nrow(data)
    nvar <- ncol(data)
  }
  else if (is.data.frame(data)) {
      if (!all(sapply(data, is.numeric))) {
         stop ("Data frame contains non-numeric values")
      }
      data <- as.matrix(data)
      niter <- nrow(data)
      nvar <- ncol(data)
  }
  else {
    niter <- length(data)
    nvar <- 1
  }
  thin <- round(thin)
  if (length(start) > 1) 
    stop("Invalid start")
  if (length(end) > 1) 
    stop("Invalid end")
  if (length(thin) != 1) 
    stop("Invalid thin")
  if (missing(end)) 
    end <- start + (niter - 1) * thin
  else if (missing(start)) 
    start <- end - (niter - 1) * thin
  nobs <- floor((end - start)/thin + 1.0) ### patch
  if (niter < nobs) 
    stop("Start, end and thin incompatible with data")
  else {
    end <- start + thin * (nobs - 1)
    if (nobs < niter) 
      data <- data[1:nobs, , drop = FALSE]
  }
  attr(data, "mcpar") <- c(start, end, thin)
  attr(data, "class") <- "mcmc"
  data
}

"print.mcmc" <- function (x, ...) 
{
  x.orig <- x
  cat("Markov Chain Monte Carlo (MCMC) output:\nStart =", start(x), 
      "\nEnd =", end(x), "\nThinning interval =", thin(x), "\n")
  attr(x, "mcpar") <- NULL
  attr(x, "class") <- NULL
  NextMethod("print", ...)
  invisible(x.orig)
}


"as.matrix.mcmc" <- function (x, iters = FALSE, ...) 
{
  y <- matrix(nrow = niter(x), ncol = nvar(x) + iters)
  var.cols <- iters + 1:nvar(x)
  if (iters) 
    y[, 1] <- as.vector(time(x))
  y[, var.cols] <- x
  rownames <- character(ncol(y))
  if (iters) 
    rownames[1] <- "ITER"
  rownames[var.cols] <- varnames(x, allow.null = FALSE)
  dimnames(y) <- list(NULL, rownames)
  return(y)
}

"time.mcmc" <- function (x, ...) 
{
  x <- as.mcmc(x)
  ts(seq(from = start(x), to = end(x), by = thin(x)), start = start(x), 
     end = end(x), deltat = thin(x))
}

"window.mcmc" <- function (x, start, end, thin, ...) 
{
  ts.eps <- getOption("ts.eps")
  xmcpar <- mcpar(x)
  xstart <- xmcpar[1]
  xend <- xmcpar[2]
  xthin <- xmcpar[3]
  if (missing(thin)) 
    thin <- xthin
  else if (thin%%xthin != 0) {
    thin <- xthin
    warning("Thin value not changed")
  }
  xtime <- as.vector(time(x))
  if (missing(start)) 
    start <- xstart
  else if (length(start) != 1) 
    stop("bad value for start")
  else if (start < xstart) {
    start <- xstart
    warning("start value not changed")
  }
  if (missing(end)) 
    end <- xend
  else if (length(end) != 1) 
    stop("bad value for end")
  else if (end > xend) {
    end <- xend
    warning("end value not changed")
  }
  if (start > end) 
    stop("start cannot be after end")
  if (all(abs(xtime - start) > abs(start) * ts.eps)) {
    start <- xtime[(xtime > start) & ((start + xthin) > xtime)]
  }
  if (all(abs(end - xtime) > abs(end) * ts.eps)) {
    end <- xtime[(xtime < end) & ((end - xthin) < xtime)]
  }
  use <- 1:niter(x)
  use <- use[use >= trunc((start - xstart)/xthin + 1.5) &
             use <= trunc((end - xstart)/xthin + 1.5) &
             (use - trunc((start- xstart)/xthin + 1.5))%%(thin%/%xthin) == 0]
  y <- if (is.matrix(x)) 
    x[use, , drop = FALSE]
  else x[use]
  return(mcmc(y, start=start, end=end, thin=thin))
}

"mcpar" <- function (x) 
{
  attr(x, "mcpar")
}

"mcmcUpgrade" <- function (x) 
{
  if (inherits(x, "mcmc")) {
    if (length(dim(x)) == 3) {
      nchain <- dim(x)[3]
      xtspar <- attr(x, "tspar")
      xstart <- xtspar[1]
      xend <- xtspar[2]
      xthin <- xtspar[3]
      out <- vector("list", nchain)
      for (i in 1:nchain) {
        y <- unclass(x)[, , 1, drop = TRUE]
        attr(y, "title") <- NULL
        attr(y, "tspar") <- NULL
        out[[i]] <- mcmc(y, start = xstart, end = xend, 
                         thin = xthin)
      }
      if (nchain == 1) 
        return(out[[1]])
      else return(mcmc.list(out))
    }
    else return(x)
  }
  else stop("Can't upgrade")
}

"thin" <-
function (x, ...)
  UseMethod("thin")

"set.mfrow" <-
function (Nchains = 1, Nparms = 1, nplots = 1, sepplot = FALSE) 
{
  ## Set up dimensions of graphics window: 
  ## If only density plots OR trace plots are requested, dimensions are: 
  ##	1 x 1	if Nparms = 1 
  ##	1 X 2 	if Nparms = 2 
  ##	2 X 2 	if Nparms = 3 or 4 
  ##	3 X 2 	if Nparms = 5 or 6 or 10 - 12 
  ##	3 X 3 	if Nparms = 7 - 9 or >= 13 
  ## If both density plots AND trace plots are requested, dimensions are: 
  ##	1 x 2	if Nparms = 1 
  ##	2 X 2 	if Nparms = 2 
  ##	3 X 2 	if Nparms = 3, 5, 6, 10, 11, or 12 
  ##	4 x 2	if Nparms otherwise 
  ## If separate plots are requested for each chain, dimensions are: 
  ##	1 x 2	if Nparms = 1 & Nchains = 2 
  ##	2 X 2 	if Nparms = 2 & Nchains = 2 OR Nparms = 1 & Nchains = 3 or 4 
  ##	3 x 2	if Nparms = 3 or >= 5 & Nchains = 2  
  ##		   OR Nchains = 5 or 6 or 10 - 12 (and any Nparms) 
  ##	2 x 3	if Nparms = 2 or 4 & Nchains = 3 
  ##	4 x 2   if Nparms = 4 & Nchains = 2  
  ##		   OR Nchains = 4 & Nparms > 1 
  ##	3 x 3	if Nparms = 3 or >= 5  & Nchains = 3  
  ##		   OR Nchains = 7 - 9 or >= 13 (and any Nparms)
  mfrow <- if (sepplot && Nchains > 1 && nplots == 1) {
    ## Separate plots per chain
    ## Only one plot per variable
    if (Nchains == 2) {
      switch(min(Nparms, 5),
             c(1,2),
             c(2,2),
             c(3,2),
             c(4,2),
             c(3,2))
    }
    else if (Nchains == 3) {
      switch(min(Nparms, 5),
             c(2,2),
             c(2,3),
             c(3,3),
             c(2,3),
             c(3,3))
    }
    else if (Nchains == 4) {
      if (Nparms == 1)
        c(2,2)
      else
        c(4,2)
    }
    else if (any(Nchains == c(5,6,10,11,12)))
      c(3,2)
    else if (any(Nchains == c(7,8,9)) || Nchains >=13)
      c(3,3)
      
  }
  else {
    if (nplots==1) {
      ## One plot per variable
      mfrow <- switch(min(Nparms,13),
                      c(1,1),
                      c(1,2),
                      c(2,2),
                      c(2,2),
                      c(3,2),
                      c(3,2),
                      c(3,3),
                      c(3,3),
                      c(3,3),
                      c(3,2),
                      c(3,2),
                      c(3,2),
                      c(3,3))
    }
    else {
      ## Two plot per variable
      ##
      mfrow <- switch(min(Nparms, 13),
                      c(1,2),
                      c(2,2),
                      c(3,2),
                      c(4,2),
                      c(3,2),
                      c(3,2),
                      c(4,2),
                      c(4,2),
                      c(4,2),
                      c(3,2),
                      c(3,2),
                      c(3,2),
                      c(4,2))
    }
  }
  return(mfrow)
}