-
-
Notifications
You must be signed in to change notification settings - Fork 262
/
misc.R
1715 lines (1520 loc) · 56.4 KB
/
misc.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
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of RStan
# Copyright (C) 2012, 2013, 2014, 2015, 2016, 2017 Trustees of Columbia University
#
# RStan is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# RStan is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
filename_ext <- function(x) {
# obtain the file extension
# copied from tools package
pos <- regexpr("\\.([[:alnum:]]+)$", x)
ifelse(pos > -1L, substring(x, pos + 1L), "")
}
filename_rm_ext <- function(x) {
# remove the filename's extension
sub("\\.[^.]*$", "", x)
}
real_is_integer <- function(x) {
if (length(x) < 1L) return(TRUE)
if (any(is.infinite(x)) || any(is.nan(x))) return(FALSE)
all(floor(x) == x)
}
list_as_integer_if_doable <- function(x) {
# change the storage mode from 'real' to 'integer'
# if applicable since by default R use real.
#
# Args:
# x: A list
#
# Note:
# Ignore non-numeric vectors since we ignore
# them in rlist_var_context
#
lapply(x,
FUN = function(y) {
if (!is.numeric(y)) return(y)
if (is.integer(y)) return(y)
## this commented out is the idea in the function is.wholenumber in
## the help of is.integer
# if (isTRUE(all.equal(y, round(y), check.attributes = FALSE)))
if (real_is_integer(y)) storage.mode(y) <- "integer"
return(y)
})
}
mklist <- function(names) {
# Make a list using names
# Args:
# names: character strings of names of objects
# Note:
# Only extracted are modes of numeric and list, which
# are enough for stan
names <- unique(names)
cenv <- environment()
for (fn in rev(sys.parents())) {
env1 <- sys.frame(fn)
if (identical(env1, cenv)) next
d1 <- mget(names, envir = env1, ifnotfound = NA, inherits = FALSE, mode = "numeric")
d2 <- mget(names, envir = env1, ifnotfound = NA, inherits = FALSE, mode = "list")
na_idx1 <- is.na(d1)
na_idx2 <- is.na(d2)
na_idx <- na_idx1 & na_idx2
numf <- sum(na_idx)
if (numf > 0 && numf < length(names))
stop(paste("objects ", paste("'", names[na_idx], "'", collapse = ', ', sep = ''),
" of mode numeric and list not found", sep = ''))
if (numf == length(names)) next
r <- c(d1[!na_idx1], d2[na_idx1])
names(r) <- c(names[!na_idx1], names[na_idx1])
return(r)
}
stop(paste("objects ", paste("'", names, "'", collapse = ', ', sep = ''),
" of mode numeric and list not found", sep = ''))
}
stan_kw1 <- c('for', 'in', 'while', 'repeat', 'until', 'if', 'then', 'else',
'true', 'false')
stan_kw2 <- c('int', 'real', 'vector', 'simplex', 'ordered', 'positive_ordered',
'row_vector', 'matrix', 'corr_matrix', 'cov_matrix', 'lower', 'upper')
stan_kw3 <- c('model', 'data', 'parameters', 'quantities', 'transformed', 'generated')
cpp_kw <- c("alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", "bool",
"break", "case", "catch", "char", "char16_t", "char32_t", "class", "compl",
"const", "constexpr", "const_cast", "continue", "decltype", "default", "delete",
"do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern",
"false", "float", "for", "friend", "goto", "if", "inline", "int", "long", "mutable",
"namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq",
"private", "protected", "public", "register", "reinterpret_cast", "return",
"short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct",
"switch", "template", "this", "thread_local", "throw", "true", "try", "typedef",
"typeid", "typename", "union", "unsigned", "using", "virtual", "void", "volatile",
"wchar_t", "while", "xor", "xor_eq")
is_legal_stan_vname <- function(name) {
# Return:
# FALSE: not a lega variable name in Stan
# TRUE: maybe it is valid, but 100% sure
if (grepl('\\.', name)) return(FALSE)
if (grepl('^\\d', name)) return(FALSE)
if (grepl('__$', name)) return(FALSE)
if (name %in% stan_kw1) return(FALSE)
if (name %in% stan_kw2) return(FALSE)
if (name %in% stan_kw3) return(FALSE)
!name %in% cpp_kw
}
data_list2array <- function(x) {
# Turn a list of array to an array whose first dimension is the list
# and other dimensions being the dimensions of the array element.
# So this would allow data in Stan coded as `vector[J] y[I]`
# to read data in form a list that has I elements of vector of length J, say
#
# # I <- 4; J <- 5
# # y <- lapply(1:I, function(i) rnorm(J))
#
# Args:
# x: A list of numeric array with the same dimensions
# Returns:
# An array with the first dimension indexes the list;
# other dimensions being the dimensions of the list element (an array)
#
len <- length(x)
if (len == 0L) return(NULL)
dimx1 <- dim(x[[1]])
if (any(sapply(x, function(xi) !is.numeric(xi))))
stop("all elements of the list should be numeric")
if (is.null(dimx1)) dimx1 <- length(x[[1]])
lendimx1 <- length(dimx1)
if (len > 1) {
d <- sapply(x[-1],
function(xi) {
dimxi <- dim(xi)
if (is.null(dimxi)) dimxi <- length(xi)
identical(dimxi, dimx1)
})
if (!all(d)) stop("the dimensions for all elements (array) of the list are not same")
}
# TODO(?): check if x is numeric or array.
x <- do.call(c, x)
dim(x) <- c(dimx1, len)
aperm(x, c(lendimx1 + 1L, seq_len(lendimx1)))
}
data_preprocess <- function(data) { # , varnames) {
# Preprocess the data (list or env) to list for stan
#
# Args:
# data: A list, an environment, or a vector of character strings for names
# of objects
# * stop if there is NA; no-name lists; duplicate names
# * stop if the objects given name is not found
# * remove NULL, non-numeric elements
# * change to integers when applicable
#
# if (is.environment(data)) {
# data <- mget(varnames, envir = data, mode = "numeric",
# ifnotfound = list(NULL))
# data <- data[!sapply(data, is.null)]
# }
if (is.environment(data)) {
data <- as.list(data)
} else if (is.list(data)) {
v <- names(data)
if (is.null(v))
stop("data must be a named list")
## Stan would report error if variable is not found
## from the 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 = " "))
}
} else {
stop("data must be a list or an environment")
}
names <- names(data)
for (x in names) {
if (!is_legal_stan_vname(x))
stop(paste('data with name ', x, " is not allowed in Stan", sep = ''))
}
data <- lapply(names,
FUN = function(name) {
x <- data[[name]]
if (is.data.frame(x)) {
x <- data.matrix(x) # change data.frame to array
} else if (is.list(x)) {
x <- data_list2array(x) # list to array
} else if (is.logical(x)) {
x <- as.integer(x)
}
## Now we stop whenever we have NA in the data
## since we do not know what variables are needed
## at this point.
if (any(is.na(x))) {
stop("Stan does not support NA (in ", name, ") in data")
}
# remove those not numeric data
if (!is.numeric(x)) {
warning("data with name ", name, " is not numeric and not used")
return(NULL)
}
if (is.integer(x)) return(x)
# change those integers stored as reals to integers
if (all(abs(x) < .Machine$integer.max) && real_is_integer(x))
storage.mode(x) <- "integer"
return(x)
})
names(data) <- names
data[!sapply(data, is.null)]
}
read_model_from_con <- function(con) {
lines <- readLines(con, n = -1L, warn = FALSE)
paste(lines, collapse = '\n')
}
get_model_strcode <- function(file, model_code = '') {
# return the model code as a character string
# Args:
# file: a file or connection
# model_code: character string for one of the following
# * the name of an object of character string
# * the model code itself
#
# Returns:
# the model code with attribute model_name2,
# a name implied from file or object name,
# which can be used later when model_name is not
# specified for function stan.
if (!missing(file)) {
if (is.character(file)) {
fname <- file
model_name2 <- sub("\\.[^.]*$", "", filename_rm_ext(basename(fname)))
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")
}
model_code <- paste(readLines(file, warn = TRUE), collapse = '\n')
# the model name implied from file name, which
# will be used if model_name is not specified later
attr(model_code, "model_name2") <- model_name2
return(model_code)
}
model_name2 <- attr(model_code, "model_name2")
if (is.null(model_name2))
model_name2 <- deparse(substitute(model_code))
if (model_code != '' && is.character(model_code)) {
if (!grepl("\\{", model_code)) {
# model_code points an object that includes the model
model_name2 <- model_code
if (exists(model_code, mode = 'character', envir = parent.frame()))
model_code <- get(model_code, mode = 'character', envir = parent.frame())
} else {
# model_code includes the code itself, two cases of passing:
# 1. using another object such as stan(mode_code = scode)`
# 2. providing the string directly such stan(model_code = "")
if (grepl("\\{", model_name2))
model_name2 <- 'anon_model'
}
attr(model_code, "model_name2") <- model_name2
return(model_code)
}
stop("model file missing and empty model_code")
}
# FIXEME: implement more check on the arguments
check_args <- function(argss) {
if (FALSE) stop()
}
#
# model_code <- read_model_from_con('http://stan.googlecode.com/git/src/models/bugs_examples/vol1/dyes/dyes.stan')
# cat(model_code)
append_id <- function(file, id, suffix = '.csv') {
fname <- basename(file)
fpath <- dirname(file)
fname2 <- gsub("\\.csv[[:space:]]*$",
paste("_", id, ".csv", sep = ''),
fname)
if (fname2 == fname)
fname2 <- paste(fname, "_", id, ".csv", sep = '')
file.path(fpath, fname2)
}
check_seed <- function(seed, warn = 0) {
if (is.character(seed) && grepl("[^0-9]", seed)) {
if (warn == 0) stop("seed needs to be string of digits")
else message("seed needs to be string of digits")
return(NULL)
}
if (is.numeric(seed)) seed <- as.integer(seed)
if (is.na(seed)) seed <- sample.int(.Machine$integer.max, 1)
seed
}
is_named_list <- function(x) {
# tell if list x is a named list
if (!is.list(x)) return(FALSE)
n <- names(x)
if (is.null(n) || "" %in% n) return(FALSE)
return(TRUE)
}
## from ../inst/include/rstan/stan_args.hpp
#
# enum sampling_algo_t { NUTS = 1, HMC = 2, Metroplos = 3};
# enum optim_algo_t { Newton = 1, BFGS = 3, LBFGS = 4};
# enum sampling_metric_t { UNIT_E = 1, DIAG_E = 2, DENSE_E = 3};
# enum stan_args_method_t { SAMPLING = 1, OPTIM = 2, TEST_GRADIENT = 3};
config_argss <- function(chains, iter, warmup, thin,
init, seed, sample_file, diagnostic_file, algorithm,
control, ...) {
iter <- as.integer(iter)
if (iter < 1)
stop("parameter 'iter' should be a positive integer")
thin <- as.integer(thin)
if (thin < 1 || thin > iter)
stop("parameter 'thin' should be a positive integer less than 'iter'")
warmup <- max(0, as.integer(warmup))
if (warmup >= iter)
stop("parameter 'warmup' should be an integer less than 'iter'")
chains <- as.integer(chains)
if (chains < 1)
stop("parameter 'chains' should be a positive integer")
iters <- rep(iter, chains)
thins <- rep(thin, chains)
warmups <- rep(warmup, chains)
inits_specified <- FALSE
if (is.numeric(init)) init <- as.character(init)
if (is.character(init)) {
if (init[1] %in% c("0", "random")) inits <- rep(init[1], chains)
else inits <- rep("random", chains)
inits_specified <- TRUE
}
dotlist <- list(...)
# use chain_id argument if specified
chain_ids <- seq_len(chains)
if (!is.null(dotlist$chain_id)) {
chain_id <- as.integer(dotlist$chain_id)
if (any(duplicated(chain_id))) stop("chain_id has duplicated elements")
chain_id_len <- length(chain_id)
chain_ids <- if (chain_id_len >= chains) chain_id else {
c(chain_id, max(chain_id) + seq_len(chains - chain_id_len))
}
dotlist$chain_id <- NULL
}
if (!inits_specified && is.function(init)) {
## the function can take an argument named by chain_id
if (any(names(formals(init)) == "chain_id")) {
inits <- lapply(chain_ids, function(id) init(chain_id = id))
} else {
inits <- lapply(chain_ids, function(id) init())
}
if (!is_named_list(inits[[1]]))
stop('the function for specifying initial values need return a named list')
inits_specified <- TRUE
}
if (!inits_specified && is.list(init)) {
if (length(init) != chains)
stop("initial value list mismatchs number of chains")
if (!any(sapply(init, is.list))) {
stop("initial value list is not a list of lists")
}
inits <- init;
for (i in 1:chains) {
if (!is_named_list(inits[[i]]))
stop('the list for specifying initial values need be a named list')
}
inits_specified <- TRUE
}
if (!inits_specified) stop("wrong specification of initial values")
## only one seed is needed by virtue of the RNG
seed <- if (missing(seed)) sample.int(.Machine$integer.max, 1) else check_seed(seed)
dotlist$method <- if (!is.null(dotlist$test_grad) && dotlist$test_grad) "test_grad" else "sampling"
all_metrics <- c("unit_e", "diag_e", "dense_e")
if (!is.null(control)) {
if (!is.list(control))
stop("'control' should be a named list")
is_arg_recognizable(names(control),
c("adapt_engaged", "adapt_gamma",
"adapt_delta", "adapt_kappa", "adapt_t0",
"adapt_init_buffer", "adapt_term_buffer",
"adapt_window", "stepsize",
"stepsize_jitter", "metric", "int_time",
"max_treedepth",
"epsilon", "error"),
pre_msg = "'control' list contains unknown members of names: ",
call. = FALSE)
metric <- control$metric
if (!is.null(metric) && is.na(match(metric, all_metrics))) {
stop("metric should be one of ", paste0(paste0('"', all_metrics, '"'), collapse = ", "))
}
dotlist$control <- control
}
argss <- vector("list", chains)
## the name of arguments in the list need to
## match those in include/rstan/stan_args.hpp
for (i in 1:chains)
argss[[i]] <- list(chain_id = chain_ids[i],
iter = iters[i], thin = thins[i], seed = seed,
warmup = warmups[i], init = inits[[i]],
algorithm = algorithm)
if (!missing(sample_file) && !is.null(sample_file) && !is.na(sample_file)) {
sample_file <- writable_sample_file(sample_file)
if (chains == 1)
argss[[1]]$sample_file <- sample_file
if (chains > 1) {
for (i in 1:chains)
argss[[i]]$sample_file <- append_id(sample_file, i)
}
}
if (!missing(diagnostic_file) && !is.null(diagnostic_file) && !is.na(diagnostic_file)) {
diagnostic_file <- writable_sample_file(diagnostic_file)
if (chains == 1)
argss[[1]]$diagnostic_file <- diagnostic_file
if (chains > 1) {
for (i in 1:chains)
argss[[i]]$diagnostic_file <- append_id(diagnostic_file, i)
}
}
for (i in 1:chains)
argss[[i]] <- c(argss[[i]], dotlist)
check_args(argss)
argss
}
is_dir_writable <- function(path) {
(file.access(path, mode = 2) == 0) && (file.access(path, mode = 1) == 0)
}
writable_sample_file <-
function(file, warn = TRUE,
wfun = function(x, x2) {
paste('"', x, '" is not writable; use "', x2, '" instead', sep = '')
}) {
# Check if the path for file is writable, if not using tempdir()
#
# Args:
# file: The file interested.
# warning: TRUE give a warning.
# warningfun: A function that take two dirs for creating
# the warning message.
#
# Returns:
# If the specified file is writable, return itself.
# Otherwise, change the path to tempdir().
dir <- dirname(file)
if (is_dir_writable(dir)) return(file)
dir2 <- tempdir()
if (warn) warning(wfun(dir, dir2))
file.path(dir2, basename(file))
}
stan_rdump <- function(list, file = "", append = FALSE,
envir = parent.frame(),
width = options("width")$width, quiet = FALSE) {
# Dump an R list or environment for a model data
# to the R dump file that Stan supports.
#
# Args:
# list: a vector of character for all variables interested
# (the same as in R's dump function)
# file: the output file for dumping the variables.
# append: then TRUE, the file is opened with
# mode of appending; otherwise, a new file
# is created.
# quiet: no warning if TRUE
#
# Return:
if (is.character(file)) {
ex <- sapply(list, exists, envir = envir)
if (!all(ex)) {
notfound_list <- list[!ex]
if (!quiet)
warning(paste("objects not found: ", paste(notfound_list, collapse = ', '), sep = ''))
}
list <- list[ex]
if (!any(ex))
return(invisible(character()))
if (nzchar(file)) {
file <- file(file, ifelse(append, "a", "w"))
on.exit(close(file), add = TRUE)
} else {
file <- stdout()
}
}
for (x in list) {
if (!is_legal_stan_vname(x) & !quiet)
warning(paste("variable name ", x, " is not allowed in Stan", sep = ''))
}
l2 <- NULL
addnlpat <- paste0("(.{1,", width, "})(\\s|$)")
for (v in list) {
vv <- get(v, envir)
if (is.data.frame(vv)) {
vv <- data.matrix(vv)
} else if (is.list(vv)) {
vv <- data_list2array(vv)
} else if (is.logical(vv)) {
mode(vv) <- "integer"
} else if (is.factor(vv)) {
vv <- as.integer(vv)
}
if (!is.numeric(vv)) {
if (!quiet)
warning(paste0("variable ", v, " is not supported for dumping."))
next
}
if (!is.integer(vv) && max(abs(vv)) < .Machine$integer.max && real_is_integer(vv))
storage.mode(vv) <- "integer"
if (is.vector(vv)) {
if (length(vv) == 0) {
cat(v, " <- integer(0)\n", file = file, sep = '')
next
}
if (length(vv) == 1) {
cat(v, " <- ", as.character(vv), "\n", file = file, sep = '')
next
}
str <- paste0(v, " <- \nc(", paste(vv, collapse = ', '), ")")
str <- gsub(addnlpat, '\\1\n', str)
cat(str, file = file)
l2 <- c(l2, v)
next
}
if (is.matrix(vv) || is.array(vv)) {
l2 <- c(l2, v)
vvdim <- dim(vv)
cat(v, " <- \n", file = file, sep = '')
if (length(vv) == 0) {
str <- paste0("structure(integer(0), ")
} else {
str <- paste0("structure(c(", paste(as.vector(vv), collapse = ', '), "),")
}
str <- gsub(addnlpat, '\\1\n', str)
cat(str,
".Dim = c(", paste(vvdim, collapse = ', '), "))\n", file = file, sep = '')
next
}
}
invisible(l2)
}
get_rhat_cols <- function(rhats) {
#
# Args:
# rhats: a vector of rhats
#
rhat_nan_col <- rstan_options("plot_rhat_nan_col")
rhat_large_col <- rstan_options("plot_rhat_large_col")
rhat_breaks <- rstan_options("plot_rhat_breaks")
# print(rhat_breaks)
rhat_colors <- rstan_options("plot_rhat_cols")
sapply(rhats,
FUN = function(x) {
if (is.na(x) || is.nan(x) || is.infinite(x))
return(rhat_nan_col)
for (i in 1:length(rhat_breaks)) {
if (x >= rhat_breaks[i]) next
return(rhat_colors[i])
}
rhat_large_col
})
}
plot_rhat_legend <- function(x, y, cex = 1) {
# Args
# x, y: left, bottom corner coordinates
# cex: cex for the labels
rhat_breaks <- rstan_options("plot_rhat_breaks")
n_breaks <- length(rhat_breaks)
rhat_colors <- rstan_options("plot_rhat_cols")[1:n_breaks]
rhat_legend_labels <- c(paste("< ", rhat_breaks, " ", sep = ''),
paste(">= ", max(rhat_breaks), " ", sep = ''),
"NaN/Inf")
rhat_legend_cols <- c(rhat_colors, rstan_options('plot_rhat_large_col'),
rstan_options("plot_rhat_nan_col"))
rhat_legend_width <- strwidth(rhat_legend_labels, cex = cex)
rhat_rect_width <- strwidth("r-hat ", cex = cex)
text(x, y, label = 'Rhat: ', adj = c(0, 0), cex = cex)
s1 <- strwidth('Rhat: ', cex = cex)
starts <- x + c(s1, s1 + cumsum(rhat_rect_width + rhat_legend_width))
height <- strheight("0123456789<>=", cex = cex)
for (i in 1:length(rhat_legend_cols)) {
rect(starts[i], y, starts[i] + rhat_rect_width, y + height, col = rhat_legend_cols[i], border = NA)
text(starts[i] + rhat_rect_width, y, adj = c(0, 0), label = rhat_legend_labels[i], cex = cex)
}
}
read_rdump <- function(f, keep.source = FALSE, ...) {
# Read data defined in an R dump file to an R list
#
# Args:
# f: the file to be sourced
# keep.source: see doc of function source
#
# Returns:
# A list
if (missing(f))
stop("no file specified.")
e <- new.env()
source(file = f, local = e, keep.source = keep.source, ...)
as.list(e)
}
idx_col2rowm <- function(d) {
# Suppose an iteration of samples for an array parameter is ordered by
# col-major. This function generates the indexes that can be used to change
# the sequences to row-major.
# Args:
# d: the dimension of the parameter
len <- length(d)
if (0 == len) return(1)
if (1 == len) return(1:d)
idx <- aperm(array(1:prod(d), dim = d))
return(as.vector(idx))
}
idx_row2colm <- function(d) {
# What if it is row-major and we want col_major?
len <- length(d)
if (0 == len) return(1)
if (1 == len) return(1:d)
idx <- aperm(array(1:prod(d), dim = rev(d)))
return(as.vector(idx))
}
multi_idx_row2colm <- function(dims) {
# Suppose we want to change a vector of parameter names (each of which is in
# row major) to col major. This function serves to get the indexes.
# Args:
# dims: a list of dimensions for all the parameters
#
## print(dims)
shifts <- calc_starts(dims) - 1
idx <- lapply(seq_along(shifts), function(i) shifts[i] + idx_row2colm(dims[[i]]))
do.call(c, idx)
}
seq_array_ind <- function(d, col_major = FALSE) {
#
# Generate an array of indexes for an array parameter
# in order of major or column.
#
# Args:
# d: the dimensions of an array parameter, for example,
# c(2, 3).
#
# col_major: Determine what is the order of indexes.
# If col_major = TRUE, for d = c(2, 3), return
# [1, 1]
# [2, 1]
# [1, 2]
# [2, 2]
# [1, 3]
# [2, 3]
# If col_major = FALSE, for d = c(2, 3), return
# [1, 1]
# [1, 2]
# [1, 3]
# [2, 1]
# [2, 2]
# [2, 3]
#
# Returns:
# If length of d is 0, return empty vector.
# Otherwise, return an array of indexes, each
# row of which is an index.
#
# Note:
# R function arrayInd might be helpful sometimes.
#
if (length(d) == 0L)
return(numeric(0L))
total <- prod(d)
if (total == 0L)
return(array(0L, dim = 0L))
len <- length(d)
if (len == 1L)
return(array(1:total, dim = c(total, 1)))
res <- array(1L, dim = c(total, len))
# Handle cases like 1x1 matrices
if (total == 1)
return(res)
jidx <- if (col_major) 1L:len else len:1L
for (i in 2L:total) {
res[i, ] <- res[i - 1, ]
for (j in jidx) {
if (res[i - 1, j] < d[j]) {
res[i, j] <- res[i - 1, j] + 1
break
}
res[i, j] <- 1
}
}
res
}
flat_one_par <- function(n, d, col_major = FALSE) {
# Return all the elemenetwise parameters for a vector/array
# parameter.
#
# Args:
# n: Name of the parameter. For example, n = "alpha"
# d: A vector indicates the dimensions of parameter n.
# For example, d = c(2, 3). d could be empty
# as well when n is a scalar.
#
if (0 == length(d)) return(n)
nameidx <- seq_array_ind(d, col_major)
names <- apply(nameidx, 1, function(x) paste(n, "[", paste(x, collapse = ','), "]", sep = ''))
as.vector(names)
}
flatnames <- function(names, dims, col_major = FALSE) {
if (length(names) == 1)
return(flat_one_par(names, dims[[1]], col_major = col_major))
nameslst <- mapply(flat_one_par, names, dims,
MoreArgs = list(col_major = col_major),
SIMPLIFY = FALSE,
USE.NAMES = FALSE)
if (is.vector(nameslst, "character"))
return(nameslst)
do.call(c, nameslst)
}
num_pars <- function(d) prod(d)
calc_starts <- function(dims) {
len <- length(dims)
s <- sapply(unname(dims), function(d) num_pars(d), USE.NAMES = FALSE)
cumsum(c(1, s))[1:len]
}
check_pars <- function(allpars, pars) {
pars_wo_ws <- gsub('\\s+', '', pars)
m <- which(match(pars_wo_ws, allpars, nomatch = 0) == 0)
if (length(m) > 0)
stop("no parameter ", paste(pars[m], collapse = ', '))
if (length(pars_wo_ws) == 0)
stop("no parameter specified (pars is empty)")
unique(pars_wo_ws)
}
check_pars_first <- function(object, pars) {
# Check if all parameters in pars are valid parameters of the model
# Args:
# object: a stanfit object
# pars: a character vector of parameter names
# Returns:
# pars without white spaces, if any, if all are valid
# otherwise stop reporting error
allpars <- cbind(object@model_pars, flatnames(object@model_pars))
check_pars(allpars, pars)
}
check_pars_second <- function(sim, pars) {
#
# Check if all parameters in pars are parameters for which we saved
# their samples
#
# Args:
# sim: The sim slot of class stanfit
# pars: a character vector of parameter names
#
# Returns:
# pars without white spaces, if any, if all are valid
# otherwise stop reporting error
if (missing(pars)) return(sim$pars_oi)
allpars <- c(sim$pars_oi, sim$fnames_oi)
check_pars(allpars, pars)
}
remove_empty_pars <- function(pars, model_dims) {
#
# Remove parameters that are actually empty, which
# could happen when for exmample a user specify the
# following stan model code:
#
# transformed data { int n; n <- 0; }
# parameters { real y[n]; }
#
# Args:
# pars: a character vector of parameters names
# model_dims: a named list of the parameter dimension
#
# Returns:
# A character vector of parameter names with empty parameter
# being removed.
#
ind <- rep(TRUE, length(pars))
model_pars <- names(model_dims)
if (is.null(model_pars)) stop("model_dims need be a named list")
for (i in seq_along(pars)) {
p <- pars[i]
m <- match(p, model_pars)
if (!is.na(m) && prod(model_dims[[p]]) == 0) ind[i] <- FALSE
}
pars[ind]
}
pars_total_indexes <- function(names, dims, fnames, pars) {
# Obtain the total indexes for parameters (pars) in the
# whole sequences of names that is order by 'column major.'
# Args:
# names: all the parameters names specifying the sequence of parameters
# dims: the dimensions for all parameters, the order for all parameters
# should be the same with that in 'names'
# fnames: all the parameter names specified by names and dims
# pars: the parameters of interest. This function assumes that
# pars are in names.
# Note: inside each parameter (vector or array), the sequence is in terms of
# col-major. That means if we have parameter alpha and beta, the dims
# of which are [2,2] and [2,3] respectively. The whole parameter sequence
# are alpha[1,1], alpha[2,1], alpha[1,2], alpha[2,2], beta[1,1], beta[2,1],
# beta[1,2], beta[2,2], beta[1,3], beta[2,3]. In addition, for the col-majored
# sequence, an attribute named 'row_major_idx' is attached, which could
# be used when row major index is favored.
starts <- calc_starts(dims)
par_total_indexes <- function(par) {
# for just one parameter
#
p <- match(par, fnames)
# note that here when `par' is a scalar, it would
# match one of `fnames'
if (!is.na(p)) {
names(p) <- par
attr(p, "row_major_idx") <- p
return(p)
}
p <- match(par, names)
np <- num_pars(dims[[p]])
if (np == 0) return(NULL)
idx <- starts[p] + seq(0, by = 1, length.out = np)
names(idx) <- fnames[idx]
attr(idx, "row_major_idx") <- starts[p] + idx_col2rowm(dims[[p]]) - 1
idx
}
idx <- lapply(pars, FUN = par_total_indexes)
nulls <- sapply(idx, is.null)
idx <- idx[!nulls]
names(idx) <- pars[!nulls]
idx
}
rstancolgrey <- rgb(matrix(c(247, 247, 247, 204, 204, 204, 150, 150, 150, 82, 82, 82),
byrow = TRUE, ncol = 3),
alpha = 100,
names = paste(1:4), maxColorValue = 255)
# from http://colorbrewer2.org/, colorblind safe,
# 6 different colors, diverging
rstancolc <- rgb(matrix(c(230, 97, 1,
153, 142, 195,
84, 39, 136,
241, 163, 64,
216, 218, 235,
254, 224, 182),
byrow = TRUE, ncol = 3),
names = paste(1:6), maxColorValue = 255)
default_summary_probs <- function() c(0.025, 0.05, 0.10, 0.25, 0.50, 0.75, 0.90, 0.95, 0.975)
## summarize the chains merged and individually
get_par_summary <- function(sim, n, probs = default_summary_probs()) {
ss <- lapply(1:sim$chains,
function(i) {
if (sim$warmup2[i] == 0) sim$samples[[i]][[n]]
else sim$samples[[i]][[n]][-(1:sim$warmup2[i])]
})
msdfun <- function(chain) c(mean(chain, na.rm = TRUE), sd(chain, na.rm = TRUE))
qfun <- function(chain) quantile(chain, probs = probs, na.rm = TRUE)
c_msd <- unlist(lapply(ss, msdfun), use.names = FALSE)
c_quan <- unlist(lapply(ss, qfun), use.names = FALSE)
ass <- do.call(c, ss)
msd <- msdfun(ass)
quan <- qfun(ass)
list(msd = msdfun(ass), quan = qfun(ass), c_msd = c_msd, c_quan = c_quan)
}
# mean and sd
get_par_summary_msd <- function(sim, n) {
ss <- lapply(1:sim$chains,
function(i) {
if (sim$warmup2[i] == 0) sim$samples[[i]][[n]]
else sim$samples[[i]][[n]][-(1:sim$warmup2[i])]
})
sumfun <- function(chain) c(mean(chain), sd(chain))
cs <- lapply(ss, sumfun)
as <- sumfun(do.call(c, ss))
list(msd = as, c_msd = unlist(cs, use.names = FALSE))
}
# quantiles
get_par_summary_quantile <- function(sim, n, probs = default_summary_probs()) {
ss <- lapply(1:sim$chains,
function(i) {
if (sim$warmup2[i] == 0) sim$samples[[i]][[n]]
else sim$samples[[i]][[n]][-(1:sim$warmup2[i])]
})
sumfun <- function(chain) quantile(chain, probs = probs, na.rm = TRUE)
cs <- lapply(ss, sumfun)
as <- sumfun(do.call(c, ss))
list(quan = as, c_quan = unlist(cs, use.names = FALSE))
}
combine_msd_quan <- function(msd, quan) {
# Combine msd and quantiles for chain's summary
# Args:
# msd: the array for mean and sd with dim num.par * 2 * chains
# cquan: the array for quantiles with dim num.par * n.quan * chains
dim1 <- dim(msd)
dim2 <- dim(quan)
if (any(dim1[c(1, 3)] != dim2[c(1, 3)]))