-
Notifications
You must be signed in to change notification settings - Fork 2
/
stanfunc.R
2711 lines (2444 loc) · 93 KB
/
stanfunc.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
# stanfunc.R
# Note re data.table:
# ... trailing [] to prevent "doesn't print first time" bug:
# https://stackoverflow.com/questions/32988099/data-table-objects-not-printed-after-returned-from-function
# https://github.com/Rdatatable/data.table/blob/master/NEWS.md#bug-fixes-5
local({
tmp_require_package_namespace <- function(...) {
packages <- as.character(match.call(expand.dots = FALSE)[[2]])
for (p in packages) if (!requireNamespace(p)) install.packages(p)
}
tmp_require_package_namespace(
bridgesampling,
coda,
data.table,
ggplot2,
HDInterval,
matrixStats,
parallel,
reshape,
rstan,
stringr
)
})
#==============================================================================
# Namespace-like method: http://stackoverflow.com/questions/1266279/#1319786
#==============================================================================
stanfunc <- new.env()
stanfunc$DEFAULT_CHAINS <- 8
stanfunc$DEFAULT_ITER <- 2000
stanfunc$DEFAULT_INIT <- "0" # the Stan default, "random", uses the range -2 to +2
stanfunc$DEFAULT_SEED <- 1234 # for consistency across runs
stanfunc$DEFAULT_HIGH_RHAT_THRESHOLD <- 1.1
# If this threshold for R-hat is exceeded, warnings are shown. A value
# of 1.2 is a typical threshold and 1.1 is a stringent criterion (Brooks
# and Gelman 1998, doi:10.1080/10618600.1998.10474787, p. 444).
stanfunc$DEFAULT_HDI_METHOD <- "HDInterval"
stanfunc$DEFAULT_HDI_PROPORTION <- 0.95
#==============================================================================
# Core functions for e.g. rstan 2.16.2:
#==============================================================================
stanfunc$load_or_run_stan <- function(
data,
fit_filename,
model_name,
file = NULL,
model_code = "",
save_stancode_filename = NULL,
save_data_filename = NULL,
save_cpp_filename = NULL,
save_code_filename = NULL, # Deprecated; see below.
forcerun = FALSE,
chains = stanfunc$DEFAULT_CHAINS,
iter = stanfunc$DEFAULT_ITER,
init = stanfunc$DEFAULT_INIT,
seed = stanfunc$DEFAULT_SEED,
cache_filetype = c("rds", "rda"),
...)
{
# If a fit has been saved to a cache file, load and return it.
# Otherwise, run a Stan model (and save it to the cache file).
#
# Args:
# data
# Stan data, a list.
# fit_filename
# Filename of cache for fit.
# model_name
# Textual name of the model.
# file
# Filename for Stan code source. (Alternative to "model_code".)
# model_code
# Text of Stan code. (Alternative to "file".)
# save_stancode_filename
# Optional filename to save Stan code (as text).
# save_data_filename
# Optional filename to save the data, using saveRDS().
# save_cpp_filename
# Optional filename to save the Stan-generated C++ code. Unnecessary;
# both Stan and C++ code is extractable from the Stan fit.
# save_code_filename
# (DEPRECATED.) Old name for save_cpp_filename.
# forcerun
# Run Stan (and re-save the result) even if the cache exists.
# chains
# Number of chains, for Stan.
# iter
# Number of iterations, for Stan.
# init
# Method for initialization of parameters, for Stan.
# The Stan default, "random", uses the range -2 to +2.
# seed
# Random number generator seed, for Stan. For consistency across
# runs.
# cache_filetype
# Save as RDS (saveRDS/readRDS) or RDA (save/load)?
# ...
# Other arguments to rstan::stan(). Common potential parameters:
# control = list(
# adapt_delta = 0.99
# )
#
# For adapt_delta, see e.g.
# - http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
# - https://www.rdocumentation.org/packages/rstanarm/versions/2.14.1/topics/adapt_delta
if (is.null(file) == (model_code == "")) {
stop("Specify either 'file' or 'model_code' (and not both).")
}
cache_filetype <- match.arg(cache_filetype)
if (!is.null(save_code_filename)) {
if (!is.null(save_cpp_filename)) {
stop("Can't specify both 'save_code_filename' (old) and 'save_cpp_filename' (new)")
}
save_cpp_filename <- save_code_filename
}
saving <- forcerun || !file.exists(fit_filename)
# -------------------------------------------------------------------------
# Save Stan code file, if requested
# -------------------------------------------------------------------------
# ... unnecessary; both Stan and C++ code is extractable from the Stan
# fit; but helpful if the code compiles/executes but crashes with a
# line number error.
if (saving && !is.null(save_stancode_filename)) {
if (model_code == "") {
stop("Must specify 'model_code' to use 'save_stancode_filename'")
}
cat("--- Saving Stan code to file: ",
save_stancode_filename, "...\n", sep = "")
stancodefile <- file(save_stancode_filename)
writeLines(model_code, stancodefile)
close(stancodefile)
cat("... saved\n")
}
# -------------------------------------------------------------------------
# Save Stan data file, if requested. (RDS only.)
# -------------------------------------------------------------------------
if (saving && !is.null(save_data_filename)) {
cat("--- Saving Stan data to file: ",
save_data_filename, "...\n", sep = "")
saveRDS(data, file = save_data_filename)
cat("... saved\n")
}
# -------------------------------------------------------------------------
# Save C++ code file, if requested
# -------------------------------------------------------------------------
if (saving && !is.null(save_cpp_filename)) {
cat("--- Generating C++ code to save...\n")
# Note that it distinguishes between 'file' being NULL (OK) or
# missing (not).
if (!is.null(file)) {
stanc_result <- rstan::stanc(file = file)
} else {
stanc_result <- rstan::stanc(model_code = model_code)
}
cpp_code <- stanc_result$cppcode
cat("--- Saving C++ code to file: ",
save_cpp_filename, "...\n", sep = "")
cppfile <- file(save_cpp_filename)
writeLines(cpp_code, cppfile)
close(cppfile)
cat("... saved\n")
}
# -------------------------------------------------------------------------
# Load fit or run Stan
# -------------------------------------------------------------------------
if (!saving) {
# ---------------------------------------------------------------------
# Load fit
# ---------------------------------------------------------------------
if (cache_filetype == "rds") {
# .Rds
cat("Loading Stan model fit from RDS file: ",
fit_filename, "...\n", sep = "")
fit <- readRDS(fit_filename)
} else {
# .Rda, .Rdata
cat("Loading Stan model fit from RDA file: ",
fit_filename, "...\n", sep = "")
fit <- NULL # so we can detect the change when we load
load(fit_filename) # assumes it will be called 'fit'
if (class(fit) != "stanfit") {
stop(paste("No stanfit object called 'fit' in file",
fit_filename))
}
}
cat("... loaded\n")
} else {
# ---------------------------------------------------------------------
# Run Stan
# ---------------------------------------------------------------------
n_cores_stan <- getOption("mc.cores")
if (is.null(n_cores_stan)) {
n_cores_stan <- 0
# https://github.com/HenrikBengtsson/Wishlist-for-R/issues/7
}
n_cores_available <- parallel::detectCores()
if (n_cores_stan < n_cores_available) {
warning(paste0(
"Stan is not set to use all available CPU cores; using ",
n_cores_stan, " when ", n_cores_available,
" are available; retry after issuing the command\n",
" options(mc.cores = parallel::detectCores())"
))
}
if (n_cores_stan <= 1) {
warning("Running with a single CPU core; Stan may be slow")
}
cat(paste0(
"--- Running Stan, model ", model_name,
", starting at ", Sys.time(), "...\n"
))
# Stan now supports parallel operation directly
# Note that it distinguishes between 'file' being NULL (OK) or
# missing (not).
if (!is.null(file)) {
fit <- rstan::stan(
file = file,
model_name = model_name,
data = data,
chains = chains,
iter = iter,
init = init,
seed = seed,
...
)
} else {
fit <- rstan::stan(
model_code = model_code,
model_name = model_name,
data = data,
chains = chains,
iter = iter,
init = init,
seed = seed,
...
)
}
cat(paste("... Finished Stan run at", Sys.time(), "\n"))
# ---------------------------------------------------------------------
# Save fit
# ---------------------------------------------------------------------
if (cache_filetype == "rds") {
# .Rds
cat("--- Saving Stan model fit to RDS file: ",
fit_filename, "...\n", sep = "")
saveRDS(fit, file = fit_filename) # load with readRDS()
} else {
# .Rda, .Rdata
cat("--- Saving Stan model fit to RDA file: ",
fit_filename, "...\n", sep = "")
save(list = c("fit"), file = fit_filename)
}
cat("... saved\n")
}
return(fit)
}
stanfunc$load_or_run_bridge_sampler <- function(
stanfit,
filename,
assume_stanfit_from_this_R_session = FALSE,
file = NULL,
model_code = "",
data = NULL,
cores = parallel::detectCores(),
forcerun = FALSE,
algorithm = NULL, #
...)
{
# Load (from a cache) or run bridge sampling using a Stan fit object.
#
# NOTE that the Stan model must have been adapted to use
# bridgesampling-compatible methods (e.g. "target += lpdf...()... and other
# adjustments for clipped parameters), to avoid dropping constants (as Stan
# will via "~" sampling notation).
#
# Args:
# stanfit
# Stan fit object.
# filename
# Cache filename for bridgesampling results.
# assume_stanfit_from_this_R_session
# If the Stan fit was created in this R session, we can use the fit
# object directly; of not, we have to regenerate a model, which is a
# bit slower (or bridgesampling may crash).
# file
# Filename for Stan code source. (Alternative to "model_code".)
# model_code
# Text of Stan code. (Alternative to "file".)
# data
# Stan data, a list.
# cores
# Number of CPU cores to use.
# forcerun
# Run Stan (and re-save the result) even if the cache exists.
# algorithm
# Passed to rstan::stan(). See ?rstan:stan. For the rare occasions
# when you want "Fixed_param".
# ...
# Other arguments to bridgesampling::bridge_sampler().
if (!forcerun && file.exists(filename)) {
# ---------------------------------------------------------------------
# Load
# ---------------------------------------------------------------------
cat("Loading bridge_sampler() fit from RDS file: ",
filename, "...\n", sep = "")
b <- readRDS(filename)
cat("... loaded\n")
} else {
# ---------------------------------------------------------------------
# Run
# ---------------------------------------------------------------------
# POTENTIAL PROBLEM:
# Error in .local(object, ...) :
# the model object is not created or not valid
# This is a message from rstan::log_prob(stanfit).
# https://groups.google.com/forum/#!topic/stan-users/uu1p9oGIMhU
# The FIX is to specify a new stanfit_model, like this.
if (assume_stanfit_from_this_R_session) {
cat("Using existing Stan fit as stanfit_model; will crash if the",
"Stan model was created within a different R session\n")
stanfit_model <- stanfit
} else {
cat("Creating dummy compiled Stan model...\n")
if (is.null(file) == (model_code == "")) {
stop("Specify either 'file' or 'model_code' (and not both).")
}
if (is.null(data)) {
stop("data not specified")
}
if (!is.null(file)) {
stanfit_model <- rstan::stan(
file = file,
data = data, # if you use data = list(), it segfaults
chains = 1,
iter = 1, # despite the bridgesampling help, iter = 0 causes an error
algorithm = algorithm
)
} else {
stanfit_model <- rstan::stan(
model_code = model_code,
data = data,
chains = 1,
iter = 1,
algorithm = algorithm
)
}
cat("... done\n")
}
cat(paste("--- Running bridge_sampler, starting at",
Sys.time(), "...\n"))
b <- bridgesampling::bridge_sampler(
samples = stanfit,
stanfit_model = stanfit_model,
cores = cores,
...
)
cat(paste("... Finished bridge_sampler run at", Sys.time(), "\n"))
# ---------------------------------------------------------------------
# Save
# ---------------------------------------------------------------------
cat("--- Saving bridge_sampler() fit to RDS file: ",
filename, "...\n", sep = "")
saveRDS(b, file = filename) # load with readRDS()
cat("... saved\n")
}
return(b)
}
stanfunc$load_or_run_vb <- function(
data,
vbfit_filename,
model_name,
file = NULL,
model_code = "",
forcerun = FALSE,
init = stanfunc$DEFAULT_INIT,
seed = stanfunc$DEFAULT_SEED,
...)
{
if (is.null(file) == (model_code == "")) {
stop("Specify either 'file' or 'model_code' (and not both).")
}
if (!forcerun && file.exists(vbfit_filename)) {
# ---------------------------------------------------------------------
# Load
# ---------------------------------------------------------------------
cat("Loading Stan VB fit from RDS file: ",
vbfit_filename, "...\n", sep = "")
vb_fit <- readRDS(vbfit_filename)
cat("... loaded\n")
} else {
# ---------------------------------------------------------------------
# Run
# ---------------------------------------------------------------------
cat(paste0("Running variational Bayes approximation to Stan model ",
model_name, ", starting at ", Sys.time(), "...\n"))
cat("Building model...")
if (!is.null(file)) {
vb_model <- rstan::stan_model(file = file,
model_name = model_name)
} else {
vb_model <- rstan::stan_model(model_code = model_code,
model_name = model_name)
}
cat("Running VB...")
vb_fit <- rstan::vb(
object = vb_model,
data = data,
seed = seed,
init = init,
...
)
cat(paste("... Finished Stan VB run at", Sys.time(), "\n"))
# ---------------------------------------------------------------------
# Save
# ---------------------------------------------------------------------
cat("--- Saving Stan model fit to RDS file: ",
vbfit_filename, "...\n", sep = "")
saveRDS(vb_fit, file = vbfit_filename) # load with readRDS()
cat("... saved\n")
}
return(vb_fit)
}
stanfunc$quickrun <- function(
data,
model_name,
fit_cache_dir,
file = NULL,
model_code = "",
forcerun = FALSE,
chains = stanfunc$DEFAULT_CHAINS,
iter = stanfunc$DEFAULT_ITER,
init = stanfunc$DEFAULT_INIT,
seed = stanfunc$DEFAULT_SEED,
control = NULL,
vb = FALSE,
save_code = FALSE,
FIT_SUFFIX = "_stanfit.rds",
BRIDGE_SUFFIX = "_bridgesampling.rds",
VBFIT_SUFFIX = "_stanvbfit.rds",
CPP_SUFFIX = "_code.cpp",
...)
{
# A shortcut to (a) run Stan normally or via variational Bayes (VB)
# approximation, (b) if not using VB, run bridge sampling.
#
# Args:
# data
# Stan data, a list.
# model_name
# Textual name of the model.
# fit_cache_dir
# Directory in which to load/save cache information. Appropriate
# filenames are created from model_name.
# file
# Filename for Stan code source. (Alternative to "model_code".)
# model_code
# Text of Stan code. (Alternative to "file".)
# chains
# Number of chains, for Stan.
# iter
# Number of iterations, for Stan.
# init
# Method for initialization of parameters, for Stan.
# The Stan default, "random", uses the range -2 to +2.
# seed
# Random number generator seed, for Stan. For consistency across
# runs.
# control
# The Stan "control" parameter (a list), e.g. for adapt_delta. See
# above.
# vb
# Use quick-and-dirty variational Bayes approximation?
# save_code
# Save the C++ code? Unnecessary; both Stan and C++ code is
# extractable from the Stan fit.
# FIT_SUFFIX
# Suffix for building the filename for the (normal) fit cache.
# BRIDGE_SUFFIX
# Suffix for building the filename for the bridge sampling cache.
# VBFIT_SUFFIX
# Suffix for building the filename for the VB fit cache.
# CPP_SUFFIX
# Suffix for building the filename for C++ code.
# ...
# Additional parameters to rstan::stan().
if (is.null(file) == (model_code == "")) {
stop("Specify either 'file' or 'model_code' (and not both).")
}
# Note that C++ code is extractable from the Stan fit.
fit_filename <- file.path(fit_cache_dir,
paste0(model_name, FIT_SUFFIX))
bridge_filename <- file.path(fit_cache_dir,
paste0(model_name, BRIDGE_SUFFIX))
vbfit_filename <- file.path(fit_cache_dir,
paste0(model_name, VBFIT_SUFFIX))
if (save_code) {
cpp_filename <- file.path(fit_cache_dir,
paste0(model_name, CPP_SUFFIX))
} else {
cpp_filename <- NULL
}
result <- list(
model_name = model_name,
fit = NULL,
bridge = NULL,
shinystan = NULL,
vb_fit = NULL
)
if (vb) {
cat(paste0("Running variational Bayes approximation to Stan model ",
model_name, "...\n"))
result$vb_fit <- stanfunc$load_or_run_vb(
data = data,
file = file,
model_code = model_code,
vbfit_filename = vbfit_filename,
model_name = model_name,
forcerun = forcerun,
init = init,
seed = seed
)
} else {
cat(paste0("Running Stan model ", model_name, "...\n"))
# Stan fit
result$fit <- stanfunc$load_or_run_stan(
file = file,
data = standata,
model_code = model_code,
fit_filename = fit_filename,
model_name = model_name,
save_code_filename = cpp_filename,
forcerun = forcerun,
chains = chains,
iter = iter,
init = init,
seed = seed,
control = control,
...
)
# View the model in ShinyStan
cat("Making ShinyStan object...\n")
result$shinystan <- shinystan::as.shinystan(result$fit)
cat("... made\n")
# Use with: shinystan::launch_shinystan(result$shinystan)
# Bridge sampling
result$bridge <- stanfunc$load_or_run_bridge_sampler(
stanfit = result$fit,
filename = bridge_filename,
file = file,
model_code = model_code,
data = standata
)
}
return(result)
}
stanfunc$compare_model_evidence <- function(
bridgesample_list_list,
priors = NULL,
detail = FALSE,
rhat_warning_threshold = stanfunc$DEFAULT_HIGH_RHAT_THRESHOLD,
rhat_par_exclude_regex = NULL,
rhat_par_selected_regex = NULL)
{
# Compare, using bridge sampling, multiple Stan fits.
#
# Args:
# bridgesample_list_list
# A list of lists. Each item is a list with names:
# name:
# the model name
# bridgesample:
# the output from the bridgesampling::bridge_sampler()
# function (an item of class bridge_list)
# stanfit (optional):
# a corresponding Stan fit
# ... useful to show e.g. maximum R-hat summaries
# (R note: if x is a list, then if x *doesn't* have item y, x$y ==
# NULL.)
#
# new_quantile_functions:
# Optional, but can be a vector containing prior probabilities for
# each model.
#
# detail:
# Keep the details used for intermediate calculations?
#
# rhat_warning_threshold:
# If this threshold for R-hat is reached/exceeded, warnings are
# shown. A value of 1.2 is a typical threshold and 1.1 is a stringent
# criterion (Brooks and Gelman 1998,
# doi:10.1080/10618600.1998.10474787, p. 444).
#
# rhat_par_exclude_regex:
# Regex for parameters to exclude from R-hat calculation.
#
# Notes:
# - "marginal likelihood" is the same as "evidence" (e.g. Kruschke 2011
# p57-58)
# - https://stackoverflow.com/questions/9950144/access-lapply-index-names-inside-fun
# - https://stackoverflow.com/questions/4227223/r-list-to-data-frame
# - CHECK THE OUTPUT AGAINST, e.g.:
# bridgesampling::post_prob(b1, b2, b3, b4, b5, b6, model_names = paste("Model", 1:6))
# ... verified.
d <- data.table(
t(
vapply(
X = seq_along(bridgesample_list_list),
FUN = function(y, i) {
item <- y[[i]]
if (is.null(item$stanfit)) {
max_rhat <- NA_real_
} else {
fit <- item$stanfit
max_rhat <- stanfunc$max_rhat(
fit,
par_exclude_regex = rhat_par_exclude_regex
)
max_rhat_selected <- stanfunc$max_rhat(
fit,
par_regex = rhat_par_selected_regex,
par_exclude_regex = rhat_par_exclude_regex
)
}
return(c(
i, # index
item$name, # model_name
item$bridgesample$logml, # log_marginal_likelihood
max_rhat, # max_rhat
max_rhat_selected # max_rhat_selected
))
},
FUN.VALUE = c("index" = NA_integer_,
"model_name" = NA_character_,
"log_marginal_likelihood" = NA_real_,
"max_rhat" = NA_real_,
"max_rhat_selected" = NA_real_),
y = bridgesample_list_list
)
)
)
d[, index := as.numeric(index)]
d[, log_marginal_likelihood := as.numeric(log_marginal_likelihood)]
rhat_bad_label <- "WARNING: HIGH R-HAT"
rhat_good_label <- "OK"
d[, rhat_warning := ifelse(
is.na(max_rhat),
NA_character_,
ifelse(max_rhat >= rhat_warning_threshold,
rhat_bad_label, rhat_good_label)
)]
d[, rhat_selected_warning := ifelse(
is.na(max_rhat_selected),
NA_character_,
ifelse(max_rhat_selected >= rhat_warning_threshold,
rhat_bad_label, rhat_good_label)
)]
d[, model_rank := frank(-log_marginal_likelihood,
ties.method = "min")] # "sports method"
# ... bigger (less negative) is better
# ... and rank() ranks from smallest (-> 1) to biggest, so want the reverse
# ... and data.table::frank is quicker than rank (not that we care here!)
n_models <- nrow(d)
if (is.null(priors)) {
# Flat new_quantile_functions
d[, prior_p_model := 1/n_models]
} else {
# User-specified new_quantile_functions
if (length(priors) != n_models) {
stop("priors: wrong length")
}
if (sum(priors) != 1) {
warning("priors sum to ", sum(priors), ", not 1")
}
d[, prior_p_model := priors]
}
# Work with logs or everything will overflow.
d[, log_prior_p_model := log(prior_p_model)]
# e.g. Grounau 2017 eq 2:
# marginal_likelihood[i] * prior[i]
# posterior_p_model[i] = ---------------------------------------------------
# sum_over_all_j( marginal_likelihood[j] * prior[j] )
#
# Taking logs:
#
# log(posterior_p_model[i]) = log(marginal_likelihood[i]) + log(prior[i]) -
# log(sum_over_all_j( marginal_likelihood[j] * prior[j] ))
#
# and note the helpful R function matrixStats::logSumExp, where
#
# logSumExp(lx) == log(sum(exp(lx))
#
# which, for lx == log(x), means
#
# logSumExp(lx) == log(sum(x))
#
# so we will use
#
# log(marginal_likelihood[j] * prior[j]) = log(marginal_likelihood[j]) +
# log(prior[j])
d[, log_prior_times_lik :=
log_marginal_likelihood + log_prior_p_model]
d[, log_sum_prior_times_lik_all_models :=
matrixStats::logSumExp(d$log_prior_times_lik)]
d[, log_posterior_p_model :=
log_prior_times_lik - log_sum_prior_times_lik_all_models]
d[, posterior_p_model := exp(log_posterior_p_model)][]
if (!detail) {
# Remove working unless the user wants it
d[, log_prior_p_model := NULL]
d[, log_prior_times_lik := NULL]
d[, log_sum_prior_times_lik_all_models := NULL]
# d[, log_posterior_p_model := NULL][]
}
# print(d)
return(d)
}
stanfunc$sampled_values_from_stanfit <- function(
fit,
parname,
method = c("extract", "manual", "as.matrix"))
{
# Extract sampled values from a Stan fit object, for a specific parameter.
#
# Args:
# fit
# The Stan fit.
# parname
# Name of the parameter
# method
# Options:
# - manual: Laborious hand-crafted way.
# - extract: The way it's meant to be done, via rstan::extract().
# The default.
# - as.matrix: By converting the fit to a matrix.
method <- match.arg(method)
if (method == "manual") {
# 1. Laborious hand-crafted way.
n_chains <- slot(fit, "sim")$chains
n_warmup <- slot(fit, "sim")$warmup
sampled_values <- NULL
for (c in 1:n_chains) {
n_save <- slot(fit, "sim")$n_save[c]
new_values <- slot(fit, "sim")$samples[[c]][parname][[1]][(n_warmup+1):n_save]
sampled_values <- c(sampled_values, new_values)
}
} else if (method == "extract") {
# 2. The way it's meant to be done.
ex <- rstan::extract(fit, permuted = TRUE)
# Now, slightly tricky. For a plain-text parameter like "xyz", this
# is simple. For something like "subject_k[1]", it isn't so simple,
# because rstan::extract gives us proper structure.
# Can also be e.g. parname[1,1], etc.
# Grep with capture: https://stackoverflow.com/questions/952275/regex-group-capture-in-r-with-multiple-capture-groups
PARAM_WITH_INDEX_REGEX <- "^(\\w+)\\[((?:\\d+,)*\\d+)\\]$" # e.g. "somevar[3]", "blah[1,2]"
# matches <- stringr::str_match("blah", PARAM_WITH_INDEX_REGEX)
# matches <- stringr::str_match("blah[1]", PARAM_WITH_INDEX_REGEX)
# matches <- stringr::str_match("blah[2,3]", PARAM_WITH_INDEX_REGEX)
matches <- stringr::str_match(parname, PARAM_WITH_INDEX_REGEX)
if (!is.na(matches[1])) {
# parameter with index/indices e.g. "subject_k[3]", "blah[1,1]"
parname_par <- matches[2]
index_csv_numbers <- matches[3]
indices <- as.integer(unlist(strsplit(index_csv_numbers, ",")))
if (!(parname_par %in% names(ex))) {
stop("No such parameter: ", parname)
}
sampled_array <- ex[[parname_par]]
# ... for one index, sampled_array has indices [samplenum, parnum]
# so one can use sampled_values <- sampled_array[, parname_num]
# ... but for two, dim(sampled_array) is e.g. c(8000, 3, 3); this
# means 8000 samples of a 3x3 array.
# To retrieve them... see http://r.789695.n4.nabble.com/array-slice-notation-td902486.html
arraydims <- dim(sampled_array)
if (length(indices) != length(arraydims) - 1) {
stop("Bad indices for parameter: ", parname,
". Indices were: ", indices,
" and dimensions were: ", arraydims)
}
n_samples <- arraydims[1]
slicelist <- c(list(1:n_samples), as.list(indices))
# e.g. for param[3, 3], slicelist should be a list whose first
# element is 1:8000 (for 8000 samples), whose second element is 3,
# and whose third element is 3.
sampled_values <- do.call("[", c(list(sampled_array), slicelist))
} else {
# e.g. "somevar"
if (!(parname %in% names(ex))) {
stop("No such parameter: ", parname)
}
sampled_values <- ex[[parname]]
}
} else if (method == "as.matrix") {
# 3. Another...
m <- as.matrix(fit)
if (!(parname %in% colnames(m))) {
stop("No such parameter: ", parname)
}
sampled_values <- m[,parname]
} else {
stop("Bad method")
}
return(sampled_values)
}
stanfunc$summary_data_table <- function(fit, ...)
{
# Makes a data table from rstan::summary().
#
# See https://mc-stan.org/rstan/reference/stanfit-method-summary.html
#
# Args:
# ...
# Passed to rstan::summary().
# The "probs" argument is a vector of quantiles of interest (for each
# parameter).
# help("summary,stanfit-method")
s <- rstan::summary(fit, ...)
# This summary object, s, has members:
# summary = overall summary
# c_summary = per-chain summary
ss <- s$summary
parnames <- rownames(ss)
ss <- data.table(ss)
ss$parameter <- parnames
# Move the "parameters" column so it's first:
setcolorder(ss, c(ncol(ss), 1:(ncol(ss) - 1))) # make last move to first
return(ss)
}
stanfunc$summary_by_par_regex <- function(fit,
pars = NULL,
par_regex = NULL,
par_exclude_regex = NULL,
...)
{
# Calls stanfunc$summary_data_table() for a subset of parameters.
#
# Extracting parameters can be slow, so we filter parameter names before
# asking rstan to extract parameters.
if (is.null(pars)) {
pars <- names(fit) # all parameter names; this is quick
}
# Apply inclusion regex:
if (!is.null(par_regex)) {
pars <- pars[grepl(par_regex, pars)]
}
if (!is.null(par_exclude_regex)) {
pars <- pars[!grepl(par_exclude_regex, pars)]
}
if (length(pars) == 0) {
stop("No parameters selected")
}
s <- stanfunc$summary_data_table(fit, pars = pars, ...)
return(s)
}
stanfunc$params_with_high_rhat <- function(
fit,
threshold = stanfunc$DEFAULT_HIGH_RHAT_THRESHOLD,
par_exclude_regex = NULL)
{
# Returns rows from stanfunc$summary_by_par_regex() where the R-hat
# ("convergence problem") value exceeds (is worse than) a threshold.
s <- stanfunc$summary_by_par_regex(fit,
par_exclude_regex = par_exclude_regex)
return(s[Rhat >= threshold])
}
stanfunc$max_rhat <- function(fit,
par_regex = NULL,
par_exclude_regex = NULL)
{
# Returns the maximum R-hat value for any parameter in the fit meeting the
# filter criteria.
s <- stanfunc$summary_by_par_regex(fit,
par_regex = par_regex,
par_exclude_regex = par_exclude_regex)
return(max(s$Rhat))
}
stanfunc$annotated_parameters <- function(
fit,
pars = NULL,
par_regex = NULL,
par_exclude_regex = NULL,
ci = c(0.025, 0.975),
probs = c(0.025, 0.50, 0.975),
annotate = TRUE,
nonzero_as_hdi = TRUE,
hdi_proportion = stanfunc$DEFAULT_HDI_PROPORTION,
hdi_method = stanfunc$DEFAULT_HDI_METHOD,
rhat_warning_threshold = stanfunc$DEFAULT_HIGH_RHAT_THRESHOLD,
vb = FALSE
)
{
# Produces a summary table for a Stan fit, with these columns:
# parameter
# Parameter name.
# mean
# se_mean
# sd
# Usual meanings: posterior mean, standard error of the mean,
# standard deviation.
# 2.5%, 97.5% (etc.)
# The exact quantile columns used are determined by "probs". These
# are quantiles provided by stanfunc$summary_by_par_regex() and thus
# ultimately by rstan::summary().
# n_eff
# Stan measure (number of effective samples).
# Rhat
# Stan measure of convergence.
# annotation
# Added if "annotate" is TRUE; see below.
# hdi_lower
# hdi_upper