-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmcmc_analysis_tools_rstan.R
2404 lines (2084 loc) · 85.1 KB
/
mcmc_analysis_tools_rstan.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
################################################################################
#
# The code is copyright 2024 Michael Betancourt and licensed under the
# new BSD (3-clause) license:
# https://opensource.org/licenses/BSD-3-Clause
#
# For more information see https://github.com/betanalpha/mcmc_diagnostics.
#
################################################################################
# Load required libraries
library(rstan)
library(colormap)
# Graphic configuration
c_light <- c("#DCBCBC")
c_light_highlight <- c("#C79999")
c_mid <- c("#B97C7C")
c_mid_highlight <- c("#A25050")
c_dark <- c("#8F2727")
c_dark_highlight <- c("#7C0000")
c_light_teal <- c("#6B8E8E")
c_mid_teal <- c("#487575")
c_dark_teal <- c("#1D4F4F")
# Extract unpermuted expectand values from a StanFit object and format
# them for convenient access. Removes the auxiliary `lp__` variable.
# @param stan_fit A StanFit object
# @return A named list of two-dimensional arrays for each expectand in
# the StanFit object. The first dimension of each element
# indexes the Markov chains and the second dimension indexes the
# sequential states within each Markov chain.
extract_expectand_vals <- function(stan_fit) {
nom_params <- rstan:::extract(stan_fit, permuted=FALSE)
N <- dim(nom_params)[3] - 1
params <- lapply(1:N, function(n) t(nom_params[,,n]))
names(params) <- names(stan_fit)[1:N]
(params)
}
# Validate named list structure of input object.
# @param obj Object to be validated
# @param name Object name
validate_named_list <- function(obj, name) {
if ( !is.list(obj) |
is.null(names(obj)) ) {
stop(paste0('Input variable ', name, ' is not a named list.'))
}
}
# Validate two-dimensional array structure of input object.
# @param obj Object to be validated
# @param name Object name
validate_array <- function(obj, name) {
if (length(dim(obj)) != 2 | !is.double(obj) ) {
stop(paste0('Input variable ', name, ' is not a ',
'two-dimensional numeric array.'))
}
}
# Validate named list of two-dimensional array structure of input
# object.
# @param obj Object to be validated
# @param name Object name
validate_named_list_of_arrays <- function(obj, name) {
validate_named_list(obj, name)
if (!Reduce("&", sapply(obj,
function(s) is.double(s) &
length(dim(s)) == 2))) {
stop(paste0('The elements of input variable ', name,
' are not all two-dimensional numeric arrays.'))
}
dims <- sapply(obj, function(s) dim(s))
if ( !identical(unname(dims[1,][-length(dims[1,])]),
unname(dims[1,][-1])) |
!identical(unname(dims[2,][-length(dims[2,])]),
unname(dims[2,][-1])) ) {
stop(paste0('The elements of input variable ', name,
' do not have consistent dimensions.'))
}
}
# Extract Hamiltonian Monte Carlo diagnostics values from a StanFit
# object and format them for convenient access.
# @param stan_fit A StanFit object
# @return A named list of two-dimensional arrays for each expectand in
# the StanFit object. The first dimension of each element
# indexes the Markov chains and the second dimension indexes the
# sequential states within each Markov chain.
extract_hmc_diagnostics <- function(stan_fit) {
diagnostic_names <- c('divergent__', 'treedepth__', 'n_leapfrog__',
'stepsize__', 'energy__', 'accept_stat__')
nom_params <- get_sampler_params(stan_fit, inc_warmup=FALSE)
C <- length(nom_params)
params <- lapply(diagnostic_names,
function(name) t(sapply(1:C, function(c)
nom_params[c][[1]][,name])))
names(params) <- diagnostic_names
(params)
}
# Check all Hamiltonian Monte Carlo Diagnostics
# for an ensemble of Markov chains
# @param diagnostics A named list of two-dimensional arrays for
# each diagnostic. The first dimension of each
# element indexes the Markov chains and the
# second dimension indexes the sequential
# states within each Markov chain.
# @param adapt_target Target acceptance proxy statistic for step size
# adaptation.
# @param max_treedepth The maximum numerical trajectory treedepth
# @param max_width Maximum line width for printing
check_all_hmc_diagnostics <- function(diagnostics,
adapt_target=0.801,
max_treedepth=10,
max_width=72) {
validate_named_list_of_arrays(diagnostics, 'diagnostics')
no_warning <- TRUE
no_divergence_warning <- TRUE
no_treedepth_warning <- TRUE
no_efmi_warning <- TRUE
no_accept_warning <- TRUE
message <- ""
C <- dim(diagnostics[['divergent__']])[1]
S <- dim(diagnostics[['divergent__']])[2]
for (c in 1:C) {
local_message <- ""
# Check for divergences
n_div <- sum(diagnostics[['divergent__']][c,])
if (n_div > 0) {
no_warning <- FALSE
no_divergence_warning <- FALSE
local_message <-
paste0(local_message,
sprintf(' Chain %s: %s of %s transitions (%.1f%%) ',
c, n_div, S, 100 * n_div / S),
'diverged.\n')
}
# Check for tree depth saturation
n_tds <- sum(sapply(diagnostics[['treedepth__']][c,],
function(s) s >= max_treedepth))
if (n_tds > 0) {
no_warning <- FALSE
no_treedepth_warning <- FALSE
local_message <-
paste0(local_message,
sprintf(' Chain %s: %s of %s transitions (%s%%) ',
c, n_tds, S, 100 * n_tds / S),
sprintf('saturated the maximum treedepth of %s.\n',
max_treedepth))
}
# Check the energy fraction of missing information (E-FMI)
energies = diagnostics[['energy__']][c,]
numer = sum(diff(energies)**2) / length(energies)
denom = var(energies)
efmi <- numer / denom
if (efmi < 0.2) {
no_warning <- FALSE
no_efmi_warning <- FALSE
local_message <-
paste0(local_message,
sprintf(' Chain %s: E-FMI = %.3f.\n', c, efmi))
}
# Check convergence of the stepsize adaptation
ave_accept_proxy <- mean(diagnostics[['accept_stat__']][c,])
if (ave_accept_proxy < 0.9 * adapt_target) {
no_warning <- FALSE
no_accept_warning <- FALSE
local_message <-
paste0(local_message,
sprintf(' Chain %s: Averge proxy acceptance ', c),
sprintf('statistic (%.3f) is\n', ave_accept_proxy),
' smaller than 90% of the target ',
sprintf('(%.3f).\n', adapt_target))
}
if (local_message != "") {
message <- paste0(message, local_message, '\n')
}
}
if (no_warning) {
desc <- paste0('All Hamiltonian Monte Carlo diagnostics are ',
'consistent with reliable Markov chain Monte Carlo.\n\n')
desc <- paste0(strwrap(desc, max_width, 2), collapse='\n')
message <- paste0(message, desc)
}
if (!no_divergence_warning) {
desc <- paste0('Divergent Hamiltonian transitions result from ',
'unstable numerical trajectories. These ',
'instabilities are often due to degenerate target ',
'geometry, especially "pinches". If there are ',
'only a small number of divergences then running ',
'with adept_delta larger ',
sprintf('than %.3f may reduce the ', adapt_target),
'instabilities at the cost of more expensive ',
'Hamiltonian transitions.\n\n')
desc <- paste0(strwrap(desc, max_width, 2), collapse='\n')
message <- paste0(message, desc, '\n\n')
}
if (!no_treedepth_warning) {
desc <- paste0('Numerical trajectories that saturate the ',
'maximum treedepth have terminated prematurely. ',
sprintf('Increasing max_depth above %s ', max_treedepth),
'should result in more expensive, but more ',
'efficient, Hamiltonian transitions.\n\n')
desc <- paste0(strwrap(desc, max_width, 2), collapse='\n')
message <- paste0(message, desc, '\n\n')
}
if (!no_efmi_warning) {
desc <- paste0('E-FMI below 0.2 arise when a funnel-like geometry ',
'obstructs how effectively Hamiltonian trajectories ',
'can explore the target distribution.\n\n')
desc <- paste0(strwrap(desc, max_width, 2), collapse='\n')
message <- paste0(message, desc, '\n\n')
}
if (!no_accept_warning) {
desc <- paste0('A small average proxy acceptance statistic ',
'indicates that the adaptation of the numerical ',
'integrator step size failed to converge. This is ',
'often due to discontinuous or imprecise ',
'gradients.\n\n')
desc <- paste0(strwrap(desc, max_width, 2), collapse='\n')
message <- paste0(message, desc, '\n\n')
}
cat(message)
}
# Plot outcome of inverse metric adaptation
# @params stan_fit A StanFit object
# @params B The number of bins for the inverse metric element histograms.
plot_inv_metric <- function(stan_fit, B=25) {
adaptation_info <- rstan:::get_adaptation_info(stan_fit)
C <- length(adaptation_info)
inv_metric_elems <- list()
for (c in 1:C) {
raw_info <- adaptation_info[[c]]
clean1 <- sub("# Adaptation terminated\n# Step size = [0-9.]*\n#",
"", raw_info)
clean2 <- sub(" [a-zA-Z ]*:\n# ", "", clean1)
clean3 <- sub("\n$", "", clean2)
inv_metric_elems[[c]] <- as.numeric(strsplit(clean3, ',')[[1]])
}
min_elem <- min(unlist(inv_metric_elems))
max_elem <- max(unlist(inv_metric_elems))
delta <- (max_elem - min_elem) / B
min_elem <- min_elem - delta
max_elem <- max_elem + delta
bins <- seq(min_elem, max_elem, delta)
B <- B + 2
max_y <- max(sapply(1:C, function(c)
max(hist(inv_metric_elems[[c]], breaks=bins, plot=FALSE)$counts)))
idx <- rep(1:B, each=2)
x <- sapply(1:length(idx), function(b) if(b %% 2 == 1) bins[idx[b]]
else bins[idx[b] + 1])
par(mfrow=c(2, 2), mar = c(5, 2, 2, 1))
colors <- c(c_dark, c_mid_highlight, c_mid, c_light_highlight)
for (c in 1:C) {
counts <- hist(inv_metric_elems[[c]], breaks=bins, plot=FALSE)$counts
y <- counts[idx]
plot(x, y, type="l", main=paste("Chain", c), col=colors[c],
xlim=c(min_elem, max_elem), xlab="Inverse Metric Elements",
ylim=c(0, 1.05 * max_y), ylab="", yaxt="n")
}
}
# Display adapted symplectic integrator step sizes
# @param diagnostics A named list of two-dimensional arrays for
# each diagnostic. The first dimension of each
# element indexes the Markov chains and the
# second dimension indexes the sequential
# states within each Markov chain.
display_stepsizes <- function(diagnostics) {
validate_named_list_of_arrays(diagnostics, 'diagnostics')
stepsizes <- diagnostics[['stepsize__']]
C <- dim(stepsizes)[1]
for (c in 1:C) {
stepsize <- stepsizes[c, 1]
cat(sprintf('Chain %s: Integrator Step Size = %f\n',
c, stepsize))
}
}
# Display symplectic integrator trajectory lengths
# @param diagnostics A named list of two-dimensional arrays for
# each diagnostic. The first dimension of each
# element indexes the Markov chains and the
# second dimension indexes the sequential
# states within each Markov chain.
plot_num_leapfrogs <- function(diagnostics) {
validate_named_list_of_arrays(diagnostics, 'diagnostics')
lengths <- diagnostics[['n_leapfrog__']]
C <- dim(lengths)[1]
max_length <- max(lengths) + 1
max_count <- max(sapply(1:C, function(c) max(table(lengths[c,]))))
colors <- c(c_dark, c_mid_highlight, c_mid, c_light_highlight)
idx <- rep(1:max_length, each=2)
xs <- sapply(1:length(idx), function(b) if(b %% 2 == 0) idx[b] + 0.5
else idx[b] - 0.5)
plot(0, type="n",
xlab="Numerical Trajectory Length",
xlim=c(0.5, max_length + 0.5),
ylab="", ylim=c(0, 1.1 * max_count), yaxt='n')
for (c in 1:C) {
counts <- hist(lengths[c,],
seq(0.5, max_length + 0.5, 1),
plot=FALSE)$counts
pad_counts <- counts[idx]
lines(xs, pad_counts, lwd=2, col=colors[c])
}
}
# Display symplectic integrator trajectory lengths by Markov chain
# @param diagnostics A named list of two-dimensional arrays for
# each diagnostic. The first dimension of each
# element indexes the Markov chains and the
# second dimension indexes the sequential
# states within each Markov chain.
plot_num_leapfrogs_by_chain <- function(diagnostics) {
validate_named_list_of_arrays(diagnostics, 'diagnostics')
lengths <- diagnostics[['n_leapfrog__']]
C <- dim(lengths)[1]
max_length <- max(lengths) + 1
max_count <- max(sapply(1:C, function(c) max(table(lengths[c,]))))
colors <- c(c_dark, c_mid_highlight, c_mid, c_light_highlight)
idx <- rep(1:max_length, each=2)
xs <- sapply(1:length(idx), function(b) if(b %% 2 == 0) idx[b] + 0.5
else idx[b] - 0.5)
par(mfrow=c(2, 2), mar = c(5, 2, 2, 1))
for (c in 1:C) {
stepsize <- round(diagnostics[['stepsize__']][c,1], 3)
counts <- hist(lengths[c,],
seq(0.5, max_length + 0.5, 1),
plot=FALSE)$counts
pad_counts <- counts[idx]
plot(xs, pad_counts, type="l", lwd=2, col=colors[c],
main=paste0("Chain ", c, " (Stepsize = ", stepsize, ")"),
xlab="Numerical Trajectory Length", xlim=c(0.5, max_length + 0.5),
ylab="", ylim=c(0, 1.1 * max_count), yaxt='n')
}
}
# Display empirical average of the proxy acceptance statistic across
# each Markov chain
# @param diagnostics A named list of two-dimensional arrays for
# each diagnostic. The first dimension of each
# element indexes the Markov chains and the
# second dimension indexes the sequential
# states within each Markov chain.
display_ave_accept_proxy <- function(diagnostics) {
validate_named_list_of_arrays(diagnostics, 'diagnostics')
proxy_stats <- diagnostics[['accept_stat__']]
C <- dim(proxy_stats)[1]
for (c in 1:C) {
ave_accept_proxy <- mean(proxy_stats[c,])
cat(sprintf('Chain %s: Average proxy acceptance statistic = %.3f\n',
c, ave_accept_proxy))
}
}
# Display symplectic integrator trajectory times
# @param diagnostics A named list of two-dimensional arrays for
# each diagnostic. The first dimension of each
# element indexes the Markov chains and the
# second dimension indexes the sequential
# states within each Markov chain.
# @param B The number of histogram bins
# @param nlim Optional histogram range
plot_int_times <- function(diagnostics, B, tlim=NULL) {
validate_named_list_of_arrays(diagnostics, 'diagnostics')
lengths <- diagnostics[['n_leapfrog__']]
C <- dim(lengths)[1]
eps <- sapply(1:C, function(c) diagnostics[['stepsize__']][c, 1])
if (is.null(tlim)) {
# Automatically adjust histogram binning to range of outputs
min_t <- min(sapply(1:C, function(c) eps[c] * min(lengths[c,])))
max_t <- max(sapply(1:C, function(c) eps[c] * max(lengths[c,])))
tlim <- c(min_t, max_t)
delta <- (tlim[2] - tlim[1]) / B
bins <- seq(tlim[1] - delta, tlim[2] + delta, delta)
B = B + 2
} else {
delta <- (tlim[2] - tlim[1]) / B
bins <- seq(tlim[1], tlim[2], delta)
}
colors <- c(c_dark, c_mid_highlight, c_mid, c_light_highlight)
idx <- rep(1:B, each=2)
xs <- sapply(1:length(idx), function(b) if(b %% 2 == 1) bins[idx[b]]
else bins[idx[b] + 1])
max_counts <- 0
for (c in 1:C) {
counts <- hist(eps[c] * lengths[c,], bins, plot=FALSE)$counts
max_counts <- max(max_counts, max(counts))
}
plot(0, type="n",
xlab="Trajectory Integration Times",
xlim=tlim,
ylab="", ylim=c(0, 1.1 * max_counts), yaxt='n')
for (c in 1:C) {
counts <- hist(eps[c] * lengths[c,], bins, plot=FALSE)$counts
pad_counts <- counts[idx]
lines(xs, pad_counts, lwd=2, col=colors[c])
}
}
# Apply transformation identity, log, or logit transformation to
# named values and flatten the output. Transformation defaults to
# identity if name is not included in `transforms` dictionary. A
# ValueError is thrown if values are not properly constrained.
# @param name Expectand name.
# @param expectand_vals_list A named list of two-dimensional arrays for
# each expectand. The first dimension of
# each element indexes the Markov chains and
# the second dimension indexes the sequential
# states within each Markov chain.
# @param transforms A named list of transformation flags for each
# expectand.
# @return The transformed expectand name and a one-dimensional array of
# flattened transformation outputs.
apply_transform <- function(name, expectand_vals_list, transforms) {
t <- transforms[[name]]
if (is.null(t)) t <- 0
transformed_name <- ""
transformed_vals <- 0
if (t == 0) {
transformed_name <- name
transformed_vals <- c(t(expectand_vals_list[[name]]),
recursive=TRUE)
} else if (t == 1) {
if (min(expectand_vals_list[[name]]) <= 0) {
stop(paste0('Log transform requested for expectand ',
sprintf('%s ', name),
'but expectand values are not strictly positive.'))
}
transformed_name <- paste0('log(', name, ')')
transformed_vals <- log(c(t(expectand_vals_list[[name]]),
recursive=TRUE))
} else if (t == 2) {
if (min(expectand_vals_list[[name]]) <= 0 |
max(expectand_vals_list[[name]] >= 1)) {
stop(paste0('Logit transform requested for expectand ',
sprintf('%s ' , name),
'but expectand values are not strictly confined ',
'to the unit interval.'))
}
transformed_name <- paste0('logit(', name, ')')
transformed_vals <- sapply(c(t(expectand_vals_list[[name]]),
recursive=TRUE),
function(x) log(x / (1 - x)))
}
return (list('t_name' = transformed_name,
't_vals' = transformed_vals))
}
# Plot pairwise scatter plots with non-divergent and divergent
# transitions separated by color
# @param x_names An array of expectand names to be plotted on the x axis.
# @param y_names An array of expectand names to be plotted on the y axis.
# @param expectand_vals_list A named list of two-dimensional arrays for
# each expectand. The first dimension of
# each element indexes the Markov chains and
# the second dimension indexes the sequential
# states within each Markov chain.
# @param diagnostics A named list of two-dimensional arrays for
# each diagnostic. The first dimension of each
# element indexes the Markov chains and the
# second dimension indexes the sequential
# states within each Markov chain.
# @params transforms A named list of flags configuring which if any
# transformation to apply to each named expectand:
# 0: identity
# 1: log
# 2: logit
# @param xlim Optional global x-axis bounds for all pair plots.
# Defaults to dynamic bounds for each pair plot.
# @param ylim Optional global y-axis bounds for all pair plots.
# Defaults to dynamic bounds for each pair plot.
# @params plot_mode Plotting style configuration:
# 0: Non-divergent transitions are plotted in
# transparent red while divergent transitions are
# plotted in transparent green.
# 1: Non-divergent transitions are plotted in gray
# while divergent transitions are plotted in
# different shades of teal depending on the
# trajectory length. Transitions from shorter
# trajectories should cluster somewhat closer to
# the neighborhoods with problematic geometries.
# @param max_width Maximum line width for printing
plot_div_pairs <- function(x_names, y_names,
expectand_vals_list, diagnostics,
transforms=list(), xlim=NULL, ylim=NULL,
plot_mode=0, max_width=72) {
if (!is.vector(x_names)) {
stop('Input variable `x_names` is not an array.')
}
if (!is.vector(y_names)) {
stop('Input variable `y_names` is not an array.')
}
validate_named_list_of_arrays(expectand_vals_list,
'expectand_vals_list')
validate_named_list_of_arrays(diagnostics, 'diagnostics')
if (length(transforms) > 0)
validate_named_list(transforms, 'transforms')
# Check transform flags
for (name in names(transforms)) {
if (transforms[[name]] < 0 | transforms[[name]] > 2) {
warning <-
paste0(sprintf('The transform flag %s for expectand %s ',
transforms[[name]], name),
'is invalid. Plot will default to no transformation.')
warning <- paste0(strwrap(warning, max_width, 0), collapse='\n')
cat(warning)
}
}
# Check plot mode
if (plot_mode < 0 | plot_mode > 1) {
stop(sprintf('Invalid `plot_mode` value %s.', plot_mode))
}
# Transform expectand values
transformed_vals = list()
transformed_x_names <- c()
for (name in x_names) {
r <- apply_transform(name, expectand_vals_list, transforms)
if (is.null(r))
stop()
transformed_x_names <- c(transformed_x_names, r$t_name)
if (! r$t_name %in% transformed_vals) {
transformed_vals[[r$t_name]] <- r$t_vals
}
}
transformed_y_names <- c()
for (name in y_names) {
r <- apply_transform(name, expectand_vals_list, transforms)
if (is.null(r))
stop()
transformed_y_names <- c(transformed_y_names, r$t_name)
if (! r$t_name %in% transformed_vals) {
transformed_vals[[r$t_name]] <- r$t_vals
}
}
# Create pairs of transformed expectands, dropping duplicates
pairs <- list()
for (x_name in transformed_x_names) {
for (y_name in transformed_y_names) {
if (x_name == y_name) next
if (any(sapply(pairs, identical, c(x_name, y_name)))) next
if (any(sapply(pairs, identical, c(y_name, x_name)))) next
pairs[[length(pairs) + 1]] <- c(x_name, y_name)
}
}
# Extract non-divergent and divergent transition indices
divs <- diagnostics[['divergent__']]
C <- dim(divs)[1]
nondiv_filter <- c(sapply(1:C, function(c) divs[c,] == 0))
div_filter <- c(sapply(1:C, function(c) divs[c,] == 1))
if (plot_mode == 1) {
if (sum(div_filter) > 0) {
nlfs <- c(sapply(1:C,
function(c) diagnostics[['n_leapfrog__']][c,]))
div_nlfs <- nlfs[div_filter]
max_nlf <- max(div_nlfs)
nom_colors <- c(c_light_teal, c_mid_teal, c_dark_teal)
cmap <- colormap(colormap=nom_colors, nshades=max_nlf)
} else {
div_nlfs <- c()
nom_colors <- c(c_light_teal, c_mid_teal, c_dark_teal)
cmap <- colormap(colormap=nom_colors, nshades=1)
}
}
# Set plot layout dynamically
N_cols <- 3
N_plots <- length(pairs)
if (N_plots <= 3) {
par(mfrow=c(1, N_plots), mar = c(5, 5, 2, 1))
} else if (N_plots == 4) {
par(mfrow=c(2, 2), mar = c(5, 5, 2, 1))
} else if (N_plots == 6) {
par(mfrow=c(2, 3), mar = c(5, 5, 2, 1))
} else {
par(mfrow=c(3, N_cols), mar = c(5, 5, 2, 1))
}
# Plot
c_dark_trans <- c("#8F272780")
c_green_trans <- c("#00FF0080")
for (pair in pairs) {
x_name <- pair[1]
x_nondiv_vals <- transformed_vals[[x_name]][nondiv_filter]
x_div_vals <- transformed_vals[[x_name]][div_filter]
if (is.null(xlim)) {
xmin = min(transformed_vals[[x_name]])
xmax = max(transformed_vals[[x_name]])
local_xlim <- c(xmin, xmax)
} else {
local_xlim <- xlim
}
y_name <- pair[2]
y_nondiv_vals <- transformed_vals[[y_name]][nondiv_filter]
y_div_vals <- transformed_vals[[y_name]][div_filter]
if (is.null(ylim)) {
ymin = min(transformed_vals[[y_name]])
ymax = max(transformed_vals[[y_name]])
local_ylim <- c(ymin, ymax)
} else {
local_ylim <- ylim
}
if (plot_mode == 0) {
plot(x_nondiv_vals, y_nondiv_vals,
col=c_dark_trans, pch=16, main="",
xlab=x_name, xlim=local_xlim,
ylab=y_name, ylim=local_ylim)
points(x_div_vals, y_div_vals,
col=c_green_trans, pch=16)
}
if (plot_mode == 1) {
plot(x_nondiv_vals, y_nondiv_vals,
col="#DDDDDD", pch=16, main="",
xlab=x_name, xlim=local_xlim,
ylab=y_name, ylim=local_ylim)
points(x_div_vals, y_div_vals,
col=cmap[div_nlfs], pch=16)
}
}
}
# Compute hat{xi}, an estimate for the shape of a generalized Pareto
# distribution from a sample of positive values using the method
# introduced in "A New and Efficient Estimation Method for the
# Generalized Pareto Distribution" by Zhang and Stephens
# https://doi.org/10.1198/tech.2009.08017.
#
# Within the generalized Pareto distribution family all moments up to
# the mth order are finite if and only if
# xi < 1 / m.
#
# @params vals A one-dimensional array of positive values.
# @return Shape parameter estimate.
compute_xi_hat <- function(vals) {
N <- length(vals)
sorted_vals <- sort(vals)
# Return erroneous result if all input values are the same
if (sorted_vals[1] == sorted_vals[N]) {
return (NaN)
}
# Return erroneous result if all input values are not positive
if (sorted_vals[1] < 0) {
cat("Input values must be positive.")
return (NaN)
}
# Estimate 25% quantile
q <- sorted_vals[floor(0.25 * N + 0.5)]
if (q == sorted_vals[1]) {
return (-2)
}
# Heurstic generalized Pareto shape configuration
M <- 20 + floor(sqrt(N))
b_hat_vec <- rep(0, M)
log_w_vec <- rep(0, M)
for (m in 1:M) {
b_hat_vec[m] <- 1 / sorted_vals[N] +
(1 - sqrt(M / (m - 0.5))) / (3 * q)
if (b_hat_vec[m] != 0) {
xi_hat <- mean( log(1 - b_hat_vec[m] * sorted_vals) )
log_w_vec[m] <- N * ( log(-b_hat_vec[m] / xi_hat) - xi_hat - 1 )
} else {
log_w_vec[m] <- 0
}
}
# Remove terms that don't contribute to average to improve numerical
# stability
log_w_vec <- log_w_vec[b_hat_vec != 0]
b_hat_vec <- b_hat_vec[b_hat_vec != 0]
max_log_w <- max(log_w_vec)
b_hat <- sum(b_hat_vec * exp(log_w_vec - max_log_w)) /
sum(exp(log_w_vec - max_log_w))
mean( log (1 - b_hat * sorted_vals) )
}
# Compute empirical generalized Pareto shape for upper and lower tails
# for the given expectand values, ignoring any autocorrelation between
# the values.
# @param vals A one-dimensional array of sequential expectand values.
# @return Left and right shape estimators.
compute_tail_xi_hats <- function(vals) {
v_center <- median(vals)
# Isolate lower and upper tails which can be adequately modeled by a
# generalized Pareto shape for sufficiently well-behaved distributions
vals_left <- abs(vals[vals < v_center] - v_center)
N <- length(vals_left)
M <- min(0.2 * N, 3 * sqrt(N))
vals_left <- vals_left[M:N]
vals_right <- vals[vals > v_center] - v_center
N <- length(vals_right)
M <- min(0.2 * N, 3 * sqrt(N))
vals_right <- vals_right[M:N]
# Default to NaN if left tail is ill-defined
xi_hat_left <- NaN
if (length(vals_left) > 40)
xi_hat_left <- compute_xi_hat(vals_left)
# Default to NaN if right tail is ill-defined
xi_hat_right <- NaN
if (length(vals_right) > 40)
xi_hat_right <- compute_xi_hat(vals_right)
c(xi_hat_left, xi_hat_right)
}
# Check upper and lower tail behavior of the expectand values.
# @param expectand_vals A two-dimensional array of expectand values with
# the first dimension indexing the Markov chains
# and the second dimension indexing the sequential
# states within each Markov chain.
# @param max_width Maximum line width for printing
check_tail_xi_hats <- function(expectand_vals, max_width=72) {
validate_array(expectand_vals, 'expectand_vals')
C <- dim(expectand_vals)[1]
no_warning <- TRUE
message <- ""
for (c in 1:C) {
xi_hats <- compute_tail_xi_hats(expectand_vals[c,])
xi_hat_threshold <- 0.25
if ( is.nan(xi_hats[1]) & is.nan(xi_hats[2]) ) {
no_warning <- FALSE
body <- ' Chain %s: Both left and right hat{xi}s are NaN.\n'
message <- paste0(message, sprintf(body, c))
}
else if ( is.nan(xi_hats[1]) ) {
no_warning <- FALSE
body <- ' Chain %s: Left hat{xi} is NaN.\n'
message <- paste0(message, sprintf(body, c))
} else if ( is.nan(xi_hats[2]) ) {
no_warning <- FALSE
body <- ' Chain %s: Right hat{xi} is NaN.\n'
message <- paste0(message, sprintf(body, c))
} else if (xi_hats[1] >= xi_hat_threshold &
xi_hats[2] >= xi_hat_threshold) {
no_warning <- FALSE
body <- paste0(' Chain %s: Both left and right tail ',
'hat{xi}s (%.3f, %.3f) exceed %.2f.\n')
message <- paste0(message, sprintf(body, c,
xi_hats[1], xi_hats[2],
xi_hat_threshold))
} else if (xi_hats[1] < xi_hat_threshold &
xi_hats[2] >= xi_hat_threshold ) {
no_warning <- FALSE
body <- paste0(' Chain %s: Right tail hat{xi} (%.3f) ',
'exceeds %.2f.\n')
message <- paste0(message, sprintf(body, c, xi_hats[2],
xi_hat_threshold))
} else if (xi_hats[1] >= xi_hat_threshold &
xi_hats[2] < xi_hat_threshold ) {
no_warning <- FALSE
body <- paste0(' Chain %s: Left tail hat{xi} (%.3f) ',
'exceeds %.2f.\n')
message <- paste0(message, sprintf(body, c, xi_hats[1],
xi_hat_threshold))
}
}
if (no_warning) {
desc <- 'Expectand appears to be sufficiently integrable.\n\n'
message <- paste0(message, desc)
} else {
desc <- paste0('Large tail xi_hats suggest that the expectand ',
'might not be sufficiently integrable.\n\n')
desc <- paste0(strwrap(desc, max_width, 2), collapse='\n')
message <- paste0(message, desc)
}
cat(message)
}
# Compute empirical mean and variance of a given sequence with a single
# pass using Welford accumulators.
# @params vals A one-dimensional array of sequential expectand values.
# @return The empirical mean and variance.
welford_summary <- function(vals) {
mean <- 0
var <- 0
N <- length(vals)
for (n in 1:N) {
delta <- vals[n] - mean
mean <- mean + delta / n
var <- var + delta * (vals[n] - mean)
}
var <- var/ (N - 1)
return(c(mean, var))
}
# Check expectand values for vanishing empirical variance.
# @param expectand_vals A two-dimensional array of expectand values with
# the first dimension indexing the Markov chains
# and the second dimension indexing the sequential
# states within each Markov chain.
# @param max_width Maximum line width for printing
check_variances <- function(expectand_vals, max_width=72) {
validate_array(expectand_vals, 'expectand_vals')
C <- dim(expectand_vals)[1]
no_warning <- TRUE
message <- ""
for (c in 1:C) {
var <- welford_summary(expectand_vals[c,])[2]
if (var < 1e-10) {
body <- ' Chain %s: Expectand values are constant.\n'
message <- paste0(message, sprintf(body, c))
no_warning <- FALSE
}
}
if (no_warning) {
desc <- 'Expectand values are varying across all Markov chains.\n\n'
message <- paste0(message, desc)
} else {
desc <- paste0('If the expectand is not expected to be nearly ',
'constant then the Markov transition might be ',
'misbehaving.\n\n')
desc <- paste0(strwrap(desc, max_width, 2), collapse='\n')
message <- paste0(message, desc)
}
cat(message)
}
# Split a sequence of expectand values in half to create an initial and
# terminal Markov chains
# @params chain A sequence of expectand values derived from a single
# Markov chain.
# @return Two subsequences of expectand values.
split_chain <- function(chain) {
N <- length(chain)
M <- N %/% 2
list(chain1 <- chain[1:M], chain2 <- chain[(M + 1):N])
}
# Compute split hat{R} for the expectand values.
# @param expectand_vals A two-dimensional array of expectand values with
# the first dimension indexing the Markov chains
# and the second dimension indexing the sequential
# states within each Markov chain.
# @return Split Rhat estimate.
compute_split_rhat <- function(expectand_vals) {
validate_array(expectand_vals, 'expectand_vals')
C <- dim(expectand_vals)[1]
split_chain_vals <- unlist(lapply(1:C,
function(c)
split_chain(expectand_vals[c,])),
recursive=FALSE)
N_chains <- length(split_chain_vals)
N <- sum(sapply(1:C, function(c) length(expectand_vals[c,])))
means <- rep(0, N_chains)
vars <- rep(0, N_chains)
for (c in 1:N_chains) {
summary <- welford_summary(split_chain_vals[[c]])
means[c] <- summary[1]
vars[c] <- summary[2]
}
total_mean <- sum(means) / N_chains
W = sum(vars) / N_chains
B = N * sum(sapply(means, function(m)
(m - total_mean)**2)) / (N_chains - 1)
rhat = NaN
if (abs(W) > 1e-10)
rhat = sqrt( (N - 1 + B / W) / N )
(rhat)
}
# Compute split hat{R} for all input expectands.
# @param expectand_vals_list A named list of two-dimensional arrays for
# each expectand. The first dimension of
# each element indexes the Markov chains and
# the second dimension indexes the sequential
# states within each Markov chain.
# @return Array of split Rhat estimates.
compute_split_rhats <- function(expectand_vals_list) {
validate_named_list_of_arrays(expectand_vals_list,
'expectand_vals_list')
rhats <- c()
for (name in names(expectand_vals_list)) {
expectand_vals <- expectand_vals_list[[name]]
rhats <- c(rhats, compute_split_rhat(expectand_vals))
}
return(rhats)
}
# Check split hat{R} across the given expectand values.
# @param expectand_vals A two-dimensional array of expectand values with
# the first dimension indexing the Markov chains
# and the second dimension indexing the sequential
# states within each Markov chain.
# @param max_width Maximum line width for printing
check_rhat <- function(expectand_vals, max_width=72) {
validate_array(expectand_vals, 'expectand_vals')
rhat <- compute_split_rhat(expectand_vals)
no_warning <- TRUE
message <- ""
if (is.nan(rhat)) {