mcmc.R 18.4 KB
Newer Older
1
2
3
4
##################################
# Name: mcmc.R                   #
# Created: 2016-06-17            #
# Author: Chris Jewell           #
5
# Modified by: Poppy Miller      #
6
7
8
9
10
# Copyright: Chris Jewell 2016   #
# Purpose: MCMC Updaters for ref #
#          class DAG model.      #
##################################

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
AdaptiveSingleSiteMRW <- R6::R6Class(
  "AdaptiveSingleSiteMRW",
  public = list(
    toupdate = NA,
    naccept = NA,
    ncalls = NA,
    acceptbatch = NA,
    batchsize = NA,
    node = NA,
    tune = NA,
    initialize = function(node, tune = 0.1,
                          batchsize = 50) {
      self$naccept <- 0
      self$ncalls <- 0
      self$acceptbatch <- 0
      self$batchsize <- batchsize
      self$tune <- tune
      self$node <- node
    },
    update = function() {
        self$ncalls <- self$ncalls + 1
        old_data <- self$node$getData()
        picur <- self$node$logPosterior()

        # Propose using MHRW
        self$node$data <- old_data * exp( rnorm(1, 0, self$tune) )
        pican <- self$node$logPosterior()

        alpha <- pican - picur + log(self$node$data/old_data)
        if (is.finite(alpha) &
            log(runif(1)) < alpha) {
          self$acceptbatch <- self$acceptbatch + 1
        }
        else {
          self$node$data <- old_data
        }
      private$adapt()
    },
    acceptance = function() {
      self$naccept / self$ncalls
    }
  ),
  private = list(
    adapt =  function() {
      if ((self$ncalls > 0) &
          (self$ncalls %% self$batchsize == 0)) {
        m <- ifelse(self$acceptbatch / self$batchsize > 0.44, 1,-1)
        self$tune <-
          exp(log(self$tune) + m * min(0.05, 1.0 / sqrt(self$ncalls)))
        if(!is.finite(self$tune)) self$tune <- 1e-8
        self$naccept <-
          self$naccept + self$acceptbatch
        self$acceptbatch <- 0
      }
    }
  )
)


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
#' AdaptiveMultiMRW
#'
#' This class implements an Adaptive Multi-site Metropolis random walk
#' algorithm.
#'
#' A multivariate Gaussian proposal is used, for which the proposal variance
#' is a scaled version of the evolving empirical posterior covariance matrix.
#' See Roberts and Rosenthal (2012) Examples of Adaptive MCMC. \emph{Journal of Computational
#' and Graphical Statistics}. \bold{18}:349--367.
#'
#' Please note that no checks are performed as to the suitability of this
#' algorithm for a particular \link{StochasticNode}.  It is up to the user
#' to use the correct update algorithm for the appropriate nodes.
#'
#' @docType class
#' @name AdaptiveMultiMRW
#' @importFrom R6 R6Class
#' @keywords DAG node MCMC
#' @return Object of \code{\link{AdaptiveMultiMRW}}
#' @format Object of \code{\link{R6Class}} with methods for updating a \link{Node} instance.
#' @field cov the current covariance
#' @field burnin the number of updates to burn in
#' @field tune the current tuning matrix
#' @field naccept the number of accepted proposals
#' @field ncalls the number of times \code{update} has been called
#' @field node the node to which the updater is attached
#'
#' @section Methods:
#' \describe{
#'   \item{\code{new(node, tune = rep(0.1, length(node$getData())), burning = 100)}}{constructor takes an instance of a \link{StochasticNode}
#'   node, initial tuning vector (diagonal of adaptive tuning matrix), and number of burnin calls.}
#'   \item{\code{update()}}{when called, updates \code{node}}
#'   \item{\code{acceptance()}}{return the acceptance rate}
#' }
104
105
106
107
108
109
110
111
112
AdaptiveMultiMRW <- R6::R6Class(
  "AdaptiveMultiMRW",
  public = list(
    cov = NA,
    burnin = NA,
    tune = NA,
    naccept = NA,
    ncalls = NA,
    node = NA,
113
    initialize = function(node, tune = rep(0.1, length(node$getData())), burnin = 100)
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
    {
      self$node <- node
      self$naccept <- 0
      self$ncalls <- 0
      self$burnin <- burnin
      self$cov <- makeOnlineCov(length(self$node$data))
      updateOnlineCov(self$cov, self$node$data)
      self$tune <- diag(tune)
    },
    update = function()
    {
      self$ncalls <- self$ncalls + 1
      pCov <- NULL
      if ((runif(1) < 0.95) & (self$ncalls > self$burnin)) {
        pCov <- getOnlineCov(self$cov)
      }
      else pCov <- self$tune

      old_data <- self$node$data
      picur <- self$node$logPosterior()
134
      self$node$data <- mvtnorm::rmvnorm(1, mean = self$node$data, sigma = 5.6644*pCov/length(self$node$data))
135
136
137
138
139
140
141
142
143
144
145
146
147
148
      pican <- self$node$logPosterior()
      if(log(runif(1)) < pican - picur) {
        self$naccept <- self$naccept + 1
      }
      else {
        self$node$data <- old_data
      }
    },
    acceptance = function() {
      self$naccept / self$ncalls
    }
  )
)

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


#' AdaptiveDirMRW
#'
#' This class implements an Adaptive Multi-site Metropolis random walk
#' algorithm, constrained so the parameter vector sums to 1.
#'
#' An adaptive multivariate Gaussian proposal is used for $d-1$ elements of a $d$-dimensional parameter
#' vector contained in \code{node}, with the $d$th element updated to ensure that the vector sums to 1.
#' This makes the updater useful for Dirichlet distributed random variables.
#'
#' For details of the adaptive scheme, see Roberts and Rosenthal (2012) Examples of Adaptive MCMC. \emph{Journal of Computational
#' and Graphical Statistics}. \bold{18}:349--367.
#'
#' Please note that no checks are performed as to the suitability of this
#' algorithm for a particular \link{StochasticNode}.  It is up to the user
#' to use the correct update algorithm for the appropriate nodes.
#'
#' @docType class
#' @name AdaptiveDirMRW
#' @importFrom R6 R6Class
#' @export
#' @keywords DAG node MCMC
#' @return Object of \code{\link{AdaptiveDirMRW}}
#' @format Object of \code{\link{R6Class}} with methods for updating a \link{DirichletNode} instance.
#' @field cov the current covariance
#' @field burnin the number of updates to burn in
#' @field tune the current tuning matrix
#' @field naccept the number of accepted proposals
#' @field ncalls the number of times \code{update} has been called
#' @field node the node to which the updater is attached
#'
#' @section Methods:
#' \describe{
#'   \item{\code{new(node, toupdate = function() 1:length(node$getData()), tune = rep(0.1, length(node$getData())), burning = 100)}}{constructor takes an instance of a \link{StochasticNode}
#'   node, function to choose the indices of the elements to update (by default all elements), initial tuning vector (diagonal of adaptive tuning matrix), and the number of calls between
#'   adaptations.}
#'   \item{\code{update()}}{when called, updates \code{node}}
#'   \item{\code{acceptance()}}{return the acceptance rate}
#' }
189
AdaptiveDirMRW <- R6::R6Class(
190
  "AdaptiveDirMRW",
191
192
193
194
195
196
197
198
  public = list(
    toupdate = NA,
    naccept = NA,
    ncalls = NA,
    acceptbatch = NA,
    batchsize = NA,
    node = NA,
    tune = NA,
199
    name = NA,
200
    initialize = function(node, toupdate = function() 1:length(node$getData()),
201
                          tune = rep(0.1, length(node$getData())),
202
                          batchsize = 50, name = "name") {
203
204
205
206
      self$toupdate = toupdate
      self$naccept <- rep(0, length(node$getData()))
      self$ncalls <- 0
      self$acceptbatch <-
207
        rep(0, length(node$getData()))
208
209
210
      self$batchsize <- batchsize
      self$tune <- tune
      self$node <- node
211
      self$name <- name
212
213
    },
    update = function() {
214
215
216
217
      self$ncalls <- self$ncalls + 1
      for (j in self$toupdate()) {
        old_data <- self$node$getData()
        picur <- self$node$logPosterior()
218

219
        # Propose using MHRW
220
        if(runif(1) < 0.95) {
221
222
        self$node$data[j] <-
          rnorm(1, old_data[j], self$tune[j])
223
224
225
226
227
        }
        else {
          self$node$data[j] <-
            rnorm(1, old_data[j], 0.01)
        }
228
229
        if (any(self$node$data < 0)) {
          self$node$data <- old_data
230
231
232
          next
        }

233
234
235
        self$node$data <-
          self$node$getData() / sum(self$node$getData())
        pican <- self$node$logPosterior()
236
237
238
239

        alpha <- pican - picur
        if (is.finite(alpha) &
            log(runif(1)) < alpha) {
240
          self$acceptbatch[j] <- self$acceptbatch[j] + 1
241
242
        }
        else {
243
          self$node$data <- old_data
244
245
        }
      }
246
      if (self$ncalls %% 50 == 0) private$adapt()
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
    },
    acceptance = function() {
      self$naccept / self$ncalls
    }
  ),
  private = list(
    adapt =  function() {
      if ((self$ncalls > 0) &
          (self$ncalls %% self$batchsize == 0)) {
        m <- ifelse(self$acceptbatch / self$batchsize > 0.44, 1,-1)
        self$tune <-
          exp(log(self$tune) + m * min(0.05, 1.0 / sqrt(self$ncalls)))
        self$naccept <-
          self$naccept + self$acceptbatch
        self$acceptbatch <- self$acceptbatch * 0
      }
    }
  )
)

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


#' AdaptiveLogDirMRW
#'
#' This class implements an Adaptive Multi-site logarithmic Metropolis-Hastings random walk
#' algorithm, constrained so the parameter vector sums to 1.
#'
#' An adaptive multivariate log-Gaussian proposal is used for $d-1$ elements of a $d$-dimensional parameter
#' vector contained in \code{node}, with the $d$th element updated to ensure that the vector sums to 1.
#' This makes the updater useful for Dirichlet distributed random variables, improving on \link{AdaptiveDirMRW} by
#' ensuring proposals do not go negative.
#'
#' For details of the adaptive scheme, see Roberts and Rosenthal (2012) Examples of Adaptive MCMC. \emph{Journal of Computational
#' and Graphical Statistics}. \bold{18}:349--367.
#'
#' Please note that no checks are performed as to the suitability of this
#' algorithm for a particular \link{StochasticNode}.  It is up to the user
#' to use the correct update algorithm for the appropriate nodes.
#'
#' @docType class
#' @name AdaptiveLogDirMRW
#' @importFrom R6 R6Class
#' @export
#' @keywords DAG node MCMC
#' @return Object of \code{\link{AdaptiveLogDirMRW}}
#' @format Object of \code{\link{R6Class}} with methods for updating a \link{DirichletNode} instance.
#' @field cov the current covariance
#' @field burnin the number of updates to burn in
#' @field tune the current tuning matrix
#' @field naccept the number of accepted proposals
#' @field ncalls the number of times \code{update} has been called
#' @field node the node to which the updater is attached
#'
#' @section Methods:
#' \describe{
#'   \item{\code{new(node, toupdate = function() 1:length(node$getData()), tune = rep(0.1, length(node$getData())), burning = 100)}}{constructor takes an instance of a \link{StochasticNode}
#'   node, function to choose the indices of the elements to update (by default all elements), initial tuning vector (diagonal of adaptive tuning matrix), and number of calls between
#'   adaptations.}
#'   \item{\code{update()}}{when called, updates \code{node}}
#'   \item{\code{acceptance()}}{return the acceptance rate}
#' }
308
309
310
311
312
313
314
315
316
317
AdaptiveLogDirMRW <- R6::R6Class(
  "AdaptiveDirMRW",
  public = list(
    toupdate = NA,
    naccept = NA,
    ncalls = NA,
    acceptbatch = NA,
    batchsize = NA,
    node = NA,
    tune = NA,
318
    name = NA,
319
320
    initialize = function(node, toupdate = function() 1:length(node$getData()),
                          tune = rep(0.1, length(node$getData())),
321
                          batchsize = 50, name = "name") {
322
323
      self$toupdate = toupdate
      self$naccept <- rep(0, length(node$getData()))
324
      self$ncalls <- rep(0, length(node$getData()))
325
326
327
328
329
      self$acceptbatch <-
        rep(0, length(node$getData()))
      self$batchsize <- batchsize
      self$tune <- tune
      self$node <- node
330
      self$name <- name
331
332
    },
    update = function() {
333
334
335
      updIdx <- self$toupdate()
      for (j in updIdx) {
        self$ncalls[j] <- self$ncalls[j] + 1
336
337
338
339
        old_data <- self$node$getData()
        picur <- self$node$logPosterior()

        # Propose using MHRW
340
341
342
343
344
345
346
347
348
349
350
351
352
353
        logq <- 0
        if(runif(1) < 0.95) {
          self$node$data[j] <- old_data[j] * exp( rnorm(1, 0, self$tune[j]) )
          logq <- log(self$node$data[j] / old_data[j])
        }
        else {
          self$node$data[j] <- rnorm(1, old_data[j], 0.1)
        }

        # Trap to avoid negative numbers
        if(any(self$node$data < 0)) {
          self$node$data <- old_data
          next
        }
354
355
356
357
358

        self$node$data <-
          self$node$getData() / sum(self$node$getData())
        pican <- self$node$logPosterior()

359
        alpha <- pican - picur + logq
360

361
362
363
364
365
366
367
        if (is.finite(alpha) &
            log(runif(1)) < alpha) {
          self$acceptbatch[j] <- self$acceptbatch[j] + 1
        }
        else {
          self$node$data <- old_data
        }
368
        private$adapt(j)
369
      }
370
371
    },
    acceptance = function() {
372
      self$naccept <- self$naccept + self$acceptbatch
373
374
375
376
      self$naccept / self$ncalls
    }
  ),
  private = list(
377
378
379
380
381
382
383
384
385
386
387
388
389
    adapt =  function(j) {
      if ((self$ncalls[j] > 0) &
          (self$ncalls[j] %% self$batchsize == 0)) {
        m <- ifelse(self$acceptbatch[j] / self$batchsize > 0.44, 1,-1)
        self$tune[j] <-
          exp(log(self$tune[j]) + m * min(0.05, 1.0 / sqrt(self$ncalls[j])))
        if(!is.finite(self$tune[j])) {
          warning('AdaptiveLogDirMRW tuning variance non-finite')
          self$tune[j] <- 1e-9
        }
        self$naccept[j] <-
          self$naccept[j] + self$acceptbatch[j]
        self$acceptbatch[j] <- 0
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
      }
    }
  )
)



AdaptiveLogDirMRW2 <- R6::R6Class(
  "AdaptiveDirMRW2",
  public = list(
    toupdate = NA,
    naccept = NA,
    ncalls = NA,
    acceptbatch = NA,
    batchsize = NA,
    node = NA,
    tune = NA,
    initialize = function(node, toupdate = function() 1:length(node$data),
                          tune = rep(0.1, length(node$data)),
                          batchsize = 50) {
      self$toupdate = toupdate
      self$naccept <- rep(0, length(node$data))
412
      self$ncalls <- rep(0, length(node$data))
413
414
415
416
417
418
419
      self$acceptbatch <-
        rep(0, length(node$data))
      self$batchsize <- batchsize
      self$tune <- tune
      self$node <- node
    },
    update = function() {
420
421
422
      updIdx <- self$toupdate()
      for (j in updIdx) {
        self$ncalls[j] <- self$ncalls[j] + 1
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
        old_data <- self$node$data
        picur <- self$node$logPosterior()

        # Propose using MHRW
        self$node$data[j] <- old_data[j] * exp( rnorm(1, 0, self$tune[j]) )
        pican <- self$node$logPosterior()

        alpha <- pican - picur + log(self$node$data[j]/old_data[j])
        if (is.finite(alpha) &
            log(runif(1)) < alpha) {
          self$acceptbatch[j] <- self$acceptbatch[j] + 1
        }
        else {
          self$node$data <- old_data
        }
438
        private$adapt(j)
439
440
441
      }
    },
    acceptance = function() {
442
      self$naccept <- self$naccept + self$acceptbatch
443
444
445
446
      self$naccept / self$ncalls
    }
  ),
  private = list(
447
448
449
450
451
452
453
454
455
    adapt =  function(j) {
      if ((self$ncalls[j] > 0) &
          (self$ncalls[j] %% self$batchsize == 0)) {
        m <- ifelse(self$acceptbatch[j] / self$batchsize > 0.44, 1,-1)
        self$tune[j] <-
          exp(log(self$tune[j]) + m * min(0.05, 1.0 / sqrt(self$ncalls[j])))
        self$naccept[j] <-
          self$naccept[j] + self$acceptbatch[j]
        self$acceptbatch[j] <- 0
456
457
458
459
460
      }
    }
  )
)

461

462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
#' PoisGammaDPUpdate
#'
#' This class implements a marginal Gibbs sampler for a Dirichlet process
#' prior on the mean of a Poisson distributed random variable, with a Gamma-distributed
#' base function.
#'
#' The marginal Gibbs sampler is based on the description in Gelman et al. Bayesian Data
#' Analysis, 3rd edition, Chapter 23.
#'
#' Please note that no checks are performed as to the suitability of this
#' algorithm for a particular \link{StochasticNode}.  It is up to the user
#' to use the correct update algorithm for the appropriate nodes.
#'
#' @docType class
#' @name PoisGammaDPUpdate
#' @importFrom R6 R6Class
#' @export
#' @keywords DAG node Dirichlet-process
#' @return Object of \code{\link{PoisGammaDPUpdate}}
#' @format Object of \code{\link{R6Class}} with methods for updating a \link{DirichletProcessNode} instance.
#'
#' @section Methods:
#' \describe{
#'   \item{\code{new(node)}}{constructor takes an instance of a \link{DirichletProcessNode} \code{node}}
#'   \item{\code{update()}}{when called, updates \code{node}}
#' }
PoisGammaDPUpdate <- R6::R6Class(
489
  "DirichletProcessUpdate",
490
491
  public = list(
    node = NA,
492
493
494
495
496

    # P0 params
    alpha = NULL,
    beta = NULL,

497
    initialize = function(node) {
498
      self$node <- node
499
500
      self$alpha <- node$baseShape
      self$beta <- node$baseRate
501
502
503
504
505
    },
    update =
      function() {

        # Get y data
506
507
508
509
        y <- sapply(self$node$children, function(child)
          child$getData()) %>% rowSums
        aX <- sapply(self$node$children, function(child)
          child$parents$offset$getData()) %>% rowSums
510
511

        # Update s
512
513
        nk <- table(self$node$s) # Expensive!
        for (i in 1:length(self$node$s)) {
514
515
516
          nk_local <- as.numeric(nk)
          names(nk_local) <- names(nk)
          nk_local[self$node$s[i]] <- nk_local[self$node$s[i]] - 1
517

518
          theta <- self$node$theta$find(names(nk))
519

520
          logpi <- log(nk_local) + y[i] * log(theta) - theta * aX[i]
521
          logpiplus <- log(self$node$conc) +
522
523
524
            log(self$beta ^ self$alpha / gamma(self$alpha)) +
            lgamma(self$alpha + y[i]) -
            (self$alpha + y[i]) * log(self$beta + aX[i])
525
526
527
528

          logpi <- c(logpi, logpiplus)
          logpi[is.nan(logpi)] <- -Inf
          logpi <- logpi - max(logpi)
529
530
531
532

          pi <- exp(logpi)

          s_old <- self$node$s[i]
533
          idx <- sample(length(pi),1,prob = pi)
534
535
536
537
538

          # Check if we're adding another cluster
          # n.b. could use has.key(model$s[i], model$theta)
          #      but almost certainly slower.
          if (idx == length(pi)) {
539
            self$node$s[i] <- dequeue(self$node$idBucket)
540
            self$node$theta$insert(self$node$s[i], rgamma(1, self$alpha + y[i], self$beta + aX[i]))
541
            nk[self$node$s[i]] <- 0 # Add new class, increment later
542
543
          }
          else {
544
            self$node$s[i] <- names(pi)[idx]
545
546
          }

547
548
549
550
551
552
553
          # Update table of s counts, remove a class from theta if necessary
          nk[s_old] <-
            nk[s_old] - 1
          if ((nk[s_old] == 0) &
              (s_old != self$node$s[i]))
            # Delete class
          {
554
            self$node$theta$erase(s_old)
555
            enqueue(self$node$idBucket, s_old)
556
            nk <- nk[names(nk) != s_old]
557
          }
558
          nk[self$node$s[i]] <- nk[self$node$s[i]] + 1
559
560
        }

561
562
        # Sample theta from the conditional posterior
        for (label in self$node$theta$keys())
563
        {
564
565
          sumy <- sum(y[self$node$s == label])
          aXs <- sum(aX[self$node$s == label])
566
          self$node$theta$insert(label, rgamma(1, shape = self$alpha + sumy, rate = self$beta + aXs))
567
568
569
570
        }
      }
  )
)