[7f5774]: R / jags.R Maximize Restore History

Download this file

jags.R    533 lines (471 with data), 16.9 kB

  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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
.quiet.messages <- function(quiet)
{
.Call("quietMessages", quiet, PACKAGE="rjags")
}
print.jags <- function(x, ...)
{
cat("JAGS model:\n\n")
model <- x$model()
for (i in 1:length(model)) {
cat(model[i],"\n",sep="")
}
data <- x$data()
full <- !sapply(lapply(data, is.na), any)
if (any(full)) {
cat("Fully observed variables:\n", names(data)[full], "\n")
}
part <- !full & !sapply(lapply(data, is.na), all)
if (any(part)) {
cat("Partially observed variables:\n", names(data)[part], "\n")
}
}
jags.model <- function(file, data=sys.frame(sys.parent()), inits,
n.chains = 1, n.adapt=1000, quiet=FALSE)
{
if (missing(file)) {
stop("Model file name missing")
}
if (is.character(file)) {
fname <- file
file <- try(file(fname, "rt"))
if (inherits(file, "try-error")) {
stop(paste("Cannot open model file \"", fname, "\"", sep=""))
}
on.exit(close(file))
}
else if (!inherits(file, "connection")) {
stop("'file' must be a character string or connection")
}
## JAGS library requires a physical file, so we need to copy
## the contents of the connection to a temporary file
model.code <- readLines(file, warn=FALSE)
modfile <- tempfile()
writeLines(model.code, modfile)
if (quiet) {
.quiet.messages(TRUE)
on.exit(.quiet.messages(FALSE), add=TRUE)
}
p <- .Call("make_console", PACKAGE="rjags")
.Call("check_model", p, modfile, PACKAGE="rjags")
varnames <- .Call("get_variable_names", p, PACKAGE="rjags")
if (is.environment(data)) {
##Get a list of numeric objects from the supplied environment
data <- mget(varnames, envir=data, mode="numeric",
ifnotfound=list(NULL))
##Strip null entries
data <- data[!sapply(data, is.null)]
}
else if (is.list(data)) {
v <- names(data)
if (is.null(v)) {
stop("data must be a named list")
}
if (any(nchar(v)==0)) {
stop("unnamed variables in data list")
}
if (any(duplicated(v))) {
stop("Duplicated names in data list: ",
paste(v[duplicated(v)], collapse=" "))
}
relevant.variables <- v %in% varnames
data <- data[relevant.variables]
unused.variables <- setdiff(v, varnames)
for (i in seq(along=unused.variables)) {
warning("Unused variable \"", unused.variables[i], "\" in data")
}
}
else {
stop("data must be a list or environment")
}
.Call("compile", p, data, as.integer(n.chains), TRUE, PACKAGE="rjags")
### Setting initial values
if (!missing(inits)) {
checkParameters <- function(inits) {
if(!is.list(inits))
return (FALSE)
inames <- names(inits)
if (is.null(inames) || any(nchar(inames) == 0))
return (FALSE)
if (any(duplicated(inames)))
return (FALSE)
if (any(inames==".RNG.name")) {
rngname <- inits[[".RNG.name"]]
if (!is.character(rngname) || length(rngname) != 1)
return (FALSE)
inits[[".RNG.name"]] <- NULL
}
## Strip null initial values, but give a warning
null.inits <- sapply(inits, is.null)
if (any(null.inits)) {
warning("NULL initial values supplied for variable",
paste(inames[null.inits], sep=","))
inits <- inits[!null.inits]
}
if (!all(sapply(inits, is.numeric)))
return (FALSE)
return (TRUE)
}
setParameters <- function(inits, chain) {
if (!is.null(inits[[".RNG.name"]])) {
.Call("set_rng_name", p, inits[[".RNG.name"]],
as.integer(chain), PACKAGE="rjags")
inits[[".RNG.name"]] <- NULL
}
.Call("set_parameters", p, inits, as.integer(chain),
PACKAGE="rjags")
}
init.values <- vector("list", n.chains)
if (is.function(inits)) {
if (any(names(formals(inits)) == "chain")) {
for (i in 1:n.chains) {
init.values[[i]] <- inits(chain=i)
}
}
else {
for (i in 1:n.chains) {
init.values[[i]] <- inits()
}
}
}
else if (is.list(inits)) {
if (checkParameters(inits)) {
## Replicate initial values for all chains
for (i in 1:n.chains) {
init.values[[i]] <- inits
}
}
else if (!all(sapply(inits, checkParameters))) {
stop("Invalid initial values")
}
else {
if (length(inits) != n.chains) {
stop("Length mismatch in inits")
}
init.values <- inits
}
}
for (i in 1:n.chains) {
if (!checkParameters(init.values[[i]])) {
stop("Invalid parameters for chain ", i)
}
setParameters(init.values[[i]], i)
}
}
.Call("initialize", p, PACKAGE="rjags")
model.state <- .Call("get_state", p, PACKAGE="rjags")
model.data <- .Call("get_data", p, PACKAGE="rjags")
model <- list("ptr" = function() {p},
"data" = function() {model.data},
"model" = function() {model.code},
"state" = function(internal=FALSE)
{
if(!internal) {
for(i in 1:n.chains) {
model.state[[i]][[".RNG.state"]] <- NULL
model.state[[i]][[".RNG.name"]] <- NULL
}
}
return(model.state)
},
"nchain" = function()
{
.Call("get_nchain", p, PACKAGE="rjags")
},
"iter" = function()
{
.Call("get_iter", p, PACKAGE="rjags")
},
"sync" = function() {
model.state <<- .Call("get_state", p, PACKAGE="rjags")
},
"recompile" = function() {
## Clear the console
.Call("clear_console", p, PACKAGE="rjags")
p <<- .Call("make_console", PACKAGE="rjags")
## Write the model to a temporary file so we can re-read it
mf <- tempfile()
writeLines(model.code, mf)
.Call("check_model", p, mf, PACKAGE="rjags")
unlink(mf)
## Re-compile
.Call("compile", p, data, n.chains, FALSE, PACKAGE="rjags")
## Re-initialize
if (!is.null(model.state)) {
if (length(model.state) != n.chains) {
stop("Incorrect number of chains in saved state")
}
for (i in 1:n.chains) {
statei <- model.state[[i]]
rng <- statei[[".RNG.name"]]
if (!is.null(rng)) {
.Call("set_rng_name", p, rng, i, PACKAGE="rjags")
statei[[".RNG.name"]] <- NULL
}
.Call("set_parameters", p, statei, i, PACKAGE="rjags")
}
.Call("initialize", p, PACKAGE="rjags")
## Redo adaptation
adapting <- .Call("is_adapting", p, PACKAGE="rjags")
if(n.adapt > 0 && adapting) {
cat("Adapting\n")
.Call("update", p, n.adapt, PACKAGE="rjags")
if (!.Call("check_adaptation", p, PACKAGE="rjags")) {
warning("Adaptation incomplete");
}
}
model.state <<- .Call("get_state", p, PACKAGE="rjags")
}
invisible(NULL)
})
class(model) <- "jags"
if (n.adapt > 0) {
ok <- adapt(model, n.adapt)
if (!ok) warning("Adaptation incomplete")
}
return(model)
}
parse.varname <- function(varname) {
## Try to parse string of form "a" or "a[n,p:q,r]" where "a" is a
## variable name and n,p,q,r are integers
v <- try(parse(text=varname, n=1), silent=TRUE)
if (!is.expression(v) || length(v) != 1)
return(NULL)
v <- v[[1]]
if (is.name(v)) {
##Full node array requested
return(list(name=deparse(v)))
}
else if (is.call(v) && identical(deparse(v[[1]]), "[") && length(v) > 2) {
##Subset requested
ndim <- length(v) - 2
lower <- upper <- numeric(ndim)
if (any(nchar(sapply(v, deparse)) == 0)) {
##We have to catch empty indices here or they will cause trouble
##below
return(NULL)
}
for (i in 1:ndim) {
index <- v[[i+2]]
if (is.numeric(index)) {
##Single index
lower[i] <- upper[i] <- index
}
else if (is.call(index) && length(index) == 3 &&
identical(deparse(index[[1]]), ":") &&
is.numeric(index[[2]]) && is.numeric(index[[3]]))
{
##Index range
lower[i] <- index[[2]]
upper[i] <- index[[3]]
}
else return(NULL)
}
if (any(upper < lower))
return (NULL)
return(list(name = deparse(v[[2]]), lower=lower, upper=upper))
}
return(NULL)
}
parse.varnames <- function(varnames)
{
names <- character(length(varnames))
lower <- upper <- vector("list", length(varnames))
for (i in seq(along=varnames)) {
y <- parse.varname(varnames[i])
if (is.null(y)) {
stop(paste("Invalid variable subset", varnames[i]))
}
names[i] <- y$name
if (!is.null(y$lower)) {
lower[[i]] <- y$lower
}
if (!is.null(y$upper)) {
upper[[i]] <- y$upper
}
}
return(list(names=names, lower=lower, upper=upper))
}
jags.samples <-
function(model, variable.names, n.iter, thin=1, type="trace", ...)
{
if (class(model) != "jags")
stop("Invalid JAGS model")
if (!is.character(variable.names) || length(variable.names) == 0)
stop("variable.names must be a character vector")
if (!is.numeric(n.iter) || length(n.iter) != 1 || n.iter <= 0)
stop("n.iter must be a positive integer")
if (!is.character(type))
stop("type must be a character vector")
pn <- parse.varnames(variable.names)
.Call("set_monitors", model$ptr(), pn$names, pn$lower, pn$upper,
as.integer(thin), type, PACKAGE="rjags")
update(model, n.iter, ...)
ans <- .Call("get_monitored_values", model$ptr(), type, PACKAGE="rjags")
for (i in seq(along=ans)) {
class(ans[[i]]) <- "mcarray"
}
for (i in seq(along=variable.names)) {
.Call("clear_monitor", model$ptr(), pn$names[i], pn$lower[[i]],
pn$upper[[i]], type, PACKAGE="rjags")
}
return(ans)
}
list.samplers <- function(object)
{
if (!inherits(object, "jags")) {
stop("not a jags model object")
}
.Call("get_samplers", object$ptr(), PACKAGE="rjags")
}
list.factories <- function(type)
{
type = match.arg(type, c("sampler","monitor","rng"))
as.data.frame(.Call("get_factories", type, PACKAGE="rjags"))
}
set.factory <- function(name, type, state)
{
if (!is.character(name) || length(name) != 1)
stop("invalid name")
if (!is.character(type) || length(type) != 1)
stop("invalid name")
if (length(state) != 1)
stop("invalid state")
type <- match.arg(type, c("sampler","rng","monitor"))
.Call("set_factory_active", name, type, as.logical(state), PACKAGE="rjags")
}
coda.names <- function(basename, dim)
{
## Utility function used to get the names of the individual elements
## of a node array
if (prod(dim) == 1)
return(basename)
##Default lower and upper limits
ndim <- length(dim)
lower <- rep(1, ndim)
upper <- dim
##If the node name is a subset, we try to parse it to get the
##names of its elements. For example, if basename is "A[2:3]"
##we want to return names "A[2]", "A[3]" not "A[2:3][1]", "A[2:3][2]".
pn <- parse.varname(basename)
if (!is.null(pn) && !is.null(pn$lower) && !is.null(pn$upper)) {
if (length(pn$lower) == length(pn$upper)) {
dim2 <- pn$upper - pn$lower + 1
if (isTRUE(all.equal(dim[dim!=1], dim2[dim2!=1],
check.attributes=FALSE))) {
basename <- pn$name
lower <- pn$lower
upper <- pn$upper
ndim <- length(dim2)
}
}
}
indices <- as.character(lower[1]:upper[1])
if (ndim > 1) {
for (i in 2:ndim) {
indices <- outer(indices, lower[i]:upper[i], FUN=paste, sep=",")
}
}
paste(basename,"[",as.vector(indices),"]",sep="")
}
nchain <- function(model)
{
if (!inherits(model, "jags"))
stop("Invalid JAGS model object in nchain")
.Call("get_nchain", model$ptr(), PACKAGE="rjags")
}
coda.samples <- function(model, variable.names=NULL, n.iter, thin=1, ...)
{
start <- model$iter() + thin
out <- jags.samples(model, variable.names, n.iter, thin, type="trace", ...)
ans <- vector("list", nchain(model))
for (ch in 1:nchain(model)) {
ans.ch <- vector("list", length(out))
vnames.ch <- NULL
for (i in seq(along=out)) {
varname <- names(out)[[i]]
d <- dim(out[[i]])
if (length(d) < 3) {
stop("Invalid dimensions for sampled output")
}
vardim <- d[1:(length(d)-2)]
nvar <- prod(vardim)
niter <- d[length(d) - 1]
nchain <- d[length(d)]
values <- as.vector(out[[i]])
var.i <- matrix(NA, nrow=niter, ncol=nvar)
for (j in 1:nvar) {
var.i[,j] <- values[j + (0:(niter-1))*nvar + (ch-1)*niter*nvar]
}
vnames.ch <- c(vnames.ch, coda.names(varname, vardim))
ans.ch[[i]] <- var.i
}
ans.ch <- do.call("cbind", ans.ch)
colnames(ans.ch) <- vnames.ch
ans[[ch]] <- mcmc(ans.ch, start=start, thin=thin)
}
mcmc.list(ans)
}
load.module <- function(name, path, quiet=FALSE)
{
if (name %in% list.modules()) {
## This is a stop-gap measure as JAGS 2.1.0 does allow you
## to load the same module twice. This should be fixed in
## later versions.
return(invisible()) #Module already loaded
}
if (missing(path)) {
path = getOption("jags.moddir")
if (is.null(path)) {
stop("option jags.moddir is not set")
}
}
if (!is.character(path) || length(path) != 1)
stop("invalid path")
if (!is.character(name) || length(name) != 1)
stop("invalid name")
file <- file.path(path, paste(name, .Platform$dynlib.ext, sep=""))
if (!file.exists(file)) {
stop("File not found: ", file)
}
if (!isDLLLoaded(file)) {
## We must avoid calling dyn.load twice on the same DLL This
## may result in the DLL being unloaded and then reloaded,
## which will invalidate pointers to the distributions,
## functions and factories in the module.
dyn.load(file)
}
ok <- .Call("load_module", name, PACKAGE="rjags")
if (!ok) {
stop(paste("module", name, "not found\n"))
}
else if (!quiet) {
message("module ", name, " loaded")
}
invisible()
}
unload.module <- function(name, quiet=FALSE)
{
if (!is.character(name) || length(name) != 1)
stop("invalid name")
ok <- .Call("unload_module", name, PACKAGE="rjags")
if (!ok) {
warning(paste("module", name, "not loaded"))
}
else if (!quiet) {
cat("Module", name, "unloaded\n", sep=" ")
}
invisible()
}
list.modules <- function()
{
.Call("get_modules", PACKAGE="rjags");
}
isDLLLoaded <- function(file)
{
dll.list <- getLoadedDLLs()
for (i in seq(along=dll.list)) {
if (dll.list[[i]]["path"][1] == file)
return(TRUE)
}
return(FALSE)
}