-
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathfit.R
More file actions
2487 lines (2391 loc) · 99.3 KB
/
Copy pathfit.R
File metadata and controls
2487 lines (2391 loc) · 99.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
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
# CmdStanFit ---------------------------------------------------
#' CmdStanFit superclass
#'
#' @noRd
#' @description CmdStanMCMC, CmdStanMLE, CmdStanLaplace, CmdStanVB, CmdStanGQ
#' all share the methods of the superclass CmdStanFit and also have their own
#' unique methods.
#'
CmdStanFit <- R6::R6Class(
classname = "CmdStanFit",
public = list(
runset = NULL,
functions = NULL,
initialize = function(runset) {
checkmate::assert_r6(runset, classes = "CmdStanRun")
self$runset <- runset
private$return_codes_ <- self$runset$procs$return_codes()
private$model_methods_env_ <- new.env()
if (!is.null(runset$model_methods_env())) {
for (n in ls(runset$model_methods_env(), all.names = TRUE)) {
assign(n, get(n, runset$model_methods_env()), private$model_methods_env_)
}
}
drop_stale_model_methods(private$model_methods_env_)
self$functions <- new.env()
if (!is.null(runset$standalone_env())) {
for (n in ls(runset$standalone_env(), all.names = TRUE)) {
assign(n, get(n, runset$standalone_env()), self$functions)
}
}
if (!is.null(private$model_methods_env_$model_ptr)) {
initialize_model_pointer(private$model_methods_env_, self$data_file(), 0)
}
# Need to update the output directory path to one that can be accessed
# from Windows, for the post-processing of results
self$runset$args$output_dir <- wsl_safe_path(self$runset$args$output_dir, revert = TRUE)
invisible(self)
},
num_procs = function() {
self$runset$num_procs()
},
print = function(variables = NULL, ..., digits = 2, max_rows = getOption("cmdstanr_max_rows", 10)) {
if (is.null(private$draws_) &&
!length(self$output_files(include_failed = FALSE))) {
stop("Fitting failed. Unable to print.", call. = FALSE)
}
# filter variables before passing to summary to avoid computing anything
# that won't be printed because of max_rows
all_variables <- self$metadata()$variables
if (is.null(variables)) {
total_rows <- length(all_variables)
variables_to_print <- all_variables[seq_len(max_rows)]
} else {
matches <- matching_variables(variables, all_variables)
if (length(matches$not_found) > 0) {
stop("Can't find the following variable(s): ",
paste(matches$not_found, collapse = ", "), call. = FALSE)
}
total_rows <- length(matches$matching)
variables_to_print <- matches$matching[seq_len(max_rows)]
}
# if max_rows > length(variables_to_print) some will be NA
variables_to_print <- variables_to_print[!is.na(variables_to_print)]
out <- self$summary(variables_to_print, ...)
out <- as.data.frame(out)
out[, 1] <- base::format(out[, 1], justify = "left")
out[, -1] <- base::format(round(out[, -1], digits = digits), nsmall = digits)
for (col in grep("ess_", colnames(out), value = TRUE)) {
out[[col]] <- as.integer(out[[col]])
}
opts <- options(max.print = prod(dim(out)))
on.exit(options(max.print = opts$max.print), add = TRUE)
base::print(out, row.names = FALSE)
if (max_rows < total_rows) {
cat("\n # showing", max_rows, "of", total_rows,
"rows (change via 'max_rows' argument or 'cmdstanr_max_rows' option)\n")
}
invisible(self)
},
expose_functions = function(global = FALSE, verbose = FALSE) {
expose_stan_functions(self$functions, global, verbose)
invisible(NULL)
}
),
private = list(
draws_ = NULL,
metadata_ = NULL,
init_ = NULL,
profiles_ = NULL,
model_methods_env_ = NULL,
return_codes_ = NULL,
read_cmdstan_csv_with_cache_hint_ = function(...) {
tryCatch(
read_cmdstan_csv(...),
error = function(e) {
err_msg <- conditionMessage(e)
if (isTRUE(getOption("knitr.in.progress")) &&
isTRUE(self$runset$args$using_tempdir) &&
grepl("File does not exist:", err_msg, fixed = TRUE)) {
stop(
paste0(
err_msg,
"\n If this error happened during a cached Quarto or R Markdown render,\n",
" see `cmdstanr_output_dir` in `?cmdstanr_global_options`"
),
call. = FALSE
)
}
stop(e)
}
)
}
)
)
#' Save fitted model object to a file
#'
#' @name fit-method-save_object
#' @aliases save_object
#' @description This method is a wrapper around [base::saveRDS()] that ensures
#' that all posterior draws and diagnostics are saved when saving a fitted
#' model object. Because the contents of the CmdStan output CSV files are only
#' read into R lazily (i.e., as needed), the `$save_object()` method is the
#' safest way to guarantee that everything has been read in before saving.
#'
#' If you have a big object to save, use `format = "qs2"` to save using the
#' **qs2** package.
#'
#' See the "Saving fitted model objects" section of the
#' [_Getting started with CmdStanR_](https://mc-stan.org/cmdstanr/articles/cmdstanr.html)
#' vignette for some suggestions on faster model saving for large models.
#'
#' @param file (string) Path where the file should be saved.
#' @param format (string) Serialization format for the object. The default is
#' `"rds"`. The `"qs2"` format uses `qs2::qs_save()` and requires the **qs2**
#' package.
#' @param ... Other arguments to pass to [base::saveRDS()] (for `format = "rds"`)
#' or `qs2::qs_save()` (for `format = "qs2"`).
#'
#' @seealso [`CmdStanMCMC`], [`CmdStanMLE`], [`CmdStanVB`], [`CmdStanGQ`]
#'
#' @examples
#' \dontrun{
#' fit <- cmdstanr_example("logistic")
#'
#' temp_rds_file <- tempfile(fileext = ".RDS")
#' fit$save_object(file = temp_rds_file)
#' rm(fit)
#'
#' fit <- readRDS(temp_rds_file)
#' fit$summary()
#' }
#'
save_object <- function(file, format = c("rds", "qs2"), ...) {
self$draws()
try(self$sampler_diagnostics(), silent = TRUE)
try(self$init(), silent = TRUE)
try(self$profiles(), silent = TRUE)
format <- match.arg(format)
if (format == "rds") {
saveRDS(self, file = file, ...)
} else {
if (!requireNamespace("qs2", quietly = TRUE)) {
stop("The 'qs2' package is required for format = \"qs2\".", call. = FALSE)
}
qs2::qs_save(self, file = file, ...)
}
invisible(self)
}
CmdStanFit$set("public", name = "save_object", value = save_object)
#' Extract posterior draws
#'
#' @name fit-method-draws
#' @aliases draws
#' @description Extract posterior draws after MCMC or approximate posterior
#' draws after variational approximation using formats provided by the
#' \pkg{posterior} package.
#'
#' The variables include the parameters, transformed parameters, and
#' generated quantities from the Stan program as well as `lp__`, the total
#' log probability (`target`) accumulated in the model block.
#'
#' @inheritParams read_cmdstan_csv
#' @param inc_warmup (logical) Should warmup draws be included? Defaults to
#' `FALSE`. Ignored except when used with [CmdStanMCMC] objects.
#' @param format (string) The format of the returned draws or point estimates.
#' Must be a valid format from the \pkg{posterior} package. The defaults
#' are the following.
#'
#' * For sampling and generated quantities the default is
#' [`"draws_array"`][posterior::draws_array]. This format keeps the chains
#' separate. To combine the chains use any of the other formats (e.g.
#' `"draws_matrix"`).
#'
#' * For point estimates from optimization and approximate draws from
#' variational inference the default is
#' [`"draws_matrix"`][posterior::draws_array].
#'
#' To use a different format it can be specified as the full name of the
#' format from the \pkg{posterior} package (e.g. `format = "draws_df"`) or
#' omitting the `"draws_"` prefix (e.g. `format = "df"`).
#'
#' **Changing the default format**: To change the default format for an entire
#' R session use `options(cmdstanr_draws_format = format)`, where `format` is
#' the name (in quotes) of a valid format from the posterior package. For
#' example `options(cmdstanr_draws_format = "draws_df")` will change the
#' default to a data frame.
#'
#' **Note about efficiency**: For models with a large number of parameters
#' (20k+) we recommend using the `"draws_list"` format, which is the most
#' efficient and RAM friendly when combining draws from multiple chains. If
#' speed or memory is not a constraint we recommend selecting the format that
#' most suits the coding style of the post processing phase.
#'
#' @return
#' Depends on the value of `format`. The defaults are:
#' * For [MCMC][model-method-sample], a 3-D
#' [`draws_array`][posterior::draws_array] object (iteration x chain x
#' variable).
#' * For standalone [generated quantities][model-method-generate-quantities], a
#' 3-D [`draws_array`][posterior::draws_array] object (iteration x chain x
#' variable).
#' * For [variational inference][model-method-variational], a 2-D
#' [`draws_matrix`][posterior::draws_matrix] object (draw x variable) because
#' there are no chains. An additional variable `lp_approx__` is also included,
#' which is the log density of the variational approximation to the posterior
#' evaluated at each of the draws.
#' * For [optimization][model-method-optimize], a 1-row
#' [`draws_matrix`][posterior::draws_matrix] with one column per variable. These
#' are *not* actually draws, just point estimates stored in the `draws_matrix`
#' format. See [`$mle()`][fit-method-mle] to extract them as a numeric vector.
#'
#'
#' @seealso [`CmdStanMCMC`], [`CmdStanMLE`], [`CmdStanVB`], [`CmdStanGQ`]
#'
#' @examples
#' \dontrun{
#' # logistic regression with intercept alpha and coefficients beta
#' fit <- cmdstanr_example("logistic", method = "sample")
#'
#' # returned as 3-D array (see ?posterior::draws_array)
#' draws <- fit$draws()
#' dim(draws)
#' str(draws)
#'
#' # can easily convert to other formats (data frame, matrix, list)
#' # using the posterior package
#' head(posterior::as_draws_matrix(draws))
#'
#' # or can specify 'format' argument to avoid manual conversion
#' # matrix format combines all chains
#' draws <- fit$draws(format = "matrix")
#' head(draws)
#'
#' # can select specific parameters
#' fit$draws("alpha")
#' fit$draws("beta") # selects entire vector beta
#' fit$draws(c("alpha", "beta[2]"))
#'
#' # can be passed directly to bayesplot plotting functions
#' bayesplot::color_scheme_set("brightblue")
#' bayesplot::mcmc_dens(fit$draws(c("alpha", "beta")))
#' bayesplot::mcmc_scatter(fit$draws(c("beta[1]", "beta[2]")), alpha = 0.3)
#'
#'
#' # example using variational inference
#' fit <- cmdstanr_example("logistic", method = "variational")
#' head(fit$draws("beta")) # a matrix by default
#' head(fit$draws("beta", format = "df"))
#' }
#'
draws <- function(variables = NULL, inc_warmup = FALSE, format = getOption("cmdstanr_draws_format")) {
# CmdStanMCMC and CmdStanGQ have separate implementations,
# this is used for CmdStanVB and CmdStanMLE
if (is.null(format)) {
format <- "draws_matrix"
} else {
format <- assert_valid_draws_format(format)
}
if (!length(self$output_files(include_failed = FALSE))) {
stop("Fitting failed. Unable to retrieve the draws.", call. = FALSE)
}
if (inc_warmup) {
warning("'inc_warmup' is ignored except when used with CmdStanMCMC objects.",
call. = FALSE)
}
if (is.null(private$draws_)) {
private$read_csv_(format = format)
}
private$draws_ <- maybe_convert_draws_format(private$draws_, format)
posterior::subset_draws(private$draws_, variable = variables)
}
CmdStanFit$set("public", name = "draws", value = draws)
#' Extract user-specified initial values
#'
#' @name fit-method-init
#' @aliases init
#' @description Return user-specified initial values. If the user provided
#' initial values files or \R objects (list of lists or function) via the
#' `init` argument when fitting the model then these are returned (always in
#' the list of lists format). Currently it is not possible to extract initial
#' values generated automatically by CmdStan, although CmdStan may support
#' this in the future.
#'
#' @return A list of lists. See **Examples**.
#'
#' @seealso [`CmdStanMCMC`], [`CmdStanMLE`], [`CmdStanVB`]
#'
#' @examples
#' \dontrun{
#' init_fun <- function() list(alpha = rnorm(1), beta = rnorm(3))
#' fit <- cmdstanr_example("logistic", init = init_fun, chains = 2)
#' str(fit$init())
#'
#' # partial inits (only specifying for a subset of parameters)
#' init_list <- list(
#' list(mu = 10, tau = 2),
#' list(mu = -10, tau = 1)
#' )
#' fit <- cmdstanr_example("schools_ncp", init = init_list, chains = 2, adapt_delta = 0.9)
#'
#' # only user-specified inits returned
#' str(fit$init())
#' }
#'
init <- function() {
if (is.null(private$init_)) {
init_paths <- self$metadata()$init
if (!is.character(init_paths) || any(!file.exists(init_paths))) {
stop("Can't find initial values files.", call. = FALSE)
}
private$init_ <- lapply(init_paths, jsonlite::read_json, simplifyVector = TRUE)
}
private$init_
}
CmdStanFit$set("public", name = "init", value = init)
#' Compile additional methods for accessing the model log-probability function
#' and parameter constraining and unconstraining.
#'
#' @name fit-method-init_model_methods
#' @aliases init_model_methods
#'
#' @description The `$init_model_methods()` method compiles and initializes the
#' `log_prob`, `grad_log_prob`, `hessian`, `constrain_variables`,
#' `unconstrain_variables` and `unconstrain_draws` functions. These are then
#' available as methods of the fitted model object. This requires the
#' additional \pkg{Rcpp} package.
#'
#' If a model or fit object was saved with [base::saveRDS()] and later
#' reloaded, any previously compiled model-method bindings will be rebuilt in
#' the current R session when this method is called.
#'
#' Note: there may be many compiler warnings emitted during compilation but
#' these can be ignored so long as they are warnings and not errors.
#'
#' @param seed (integer) The random seed to use when initializing the model.
#' @param verbose (logical) Whether to show verbose logging during compilation.
#'
#' @examples
#' \dontrun{
#' fit_mcmc <- cmdstanr_example("logistic", method = "sample", force_recompile = TRUE)
#' # fit_mcmc$init_model_methods()
#' }
#' @seealso [log_prob()], [grad_log_prob()], [constrain_variables()],
#' [unconstrain_variables()], [unconstrain_draws()], [variable_skeleton()],
#' [hessian()]
#'
init_model_methods <- function(seed = 1, verbose = FALSE) {
if (os_is_wsl()) {
stop("Additional model methods are not currently available with ",
"WSL CmdStan and will not be compiled",
call. = FALSE)
}
require_suggested_package("Rcpp")
drop_stale_model_methods(private$model_methods_env_)
if (length(private$model_methods_env_$hpp_code_) == 0) {
stop("Model methods cannot be used with a pre-compiled Stan executable, ",
"the model must be compiled again", call. = FALSE)
}
if (is.null(private$model_methods_env_$model_ptr)) {
expose_model_methods(private$model_methods_env_, verbose)
}
if (!("model_ptr_" %in% ls(private$model_methods_env_))) {
initialize_model_pointer(private$model_methods_env_, self$data_file(), seed)
}
invisible(NULL)
}
CmdStanFit$set("public", name = "init_model_methods", value = init_model_methods)
#' Calculate the log-probability given a provided vector of unconstrained parameters.
#'
#' @name fit-method-log_prob
#' @aliases log_prob
#' @description The `$log_prob()` method provides access to the Stan model's
#' `log_prob` function.
#'
#' @param unconstrained_variables (numeric) A vector of unconstrained parameters.
#' @param jacobian (logical) Whether to include the log-density adjustments from
#' un/constraining variables.
#'
#' @examples
#' \dontrun{
#' fit_mcmc <- cmdstanr_example("logistic", method = "sample", force_recompile = TRUE)
#' fit_mcmc$log_prob(unconstrained_variables = c(0.5, 1.2, 1.1, 2.2))
#' }
#'
#' @seealso [log_prob()], [grad_log_prob()], [constrain_variables()],
#' [unconstrain_variables()], [unconstrain_draws()], [variable_skeleton()],
#' [hessian()]
#'
log_prob <- function(unconstrained_variables, jacobian = TRUE) {
self$init_model_methods()
if (length(unconstrained_variables) != private$model_methods_env_$num_upars_) {
stop("Model has ", private$model_methods_env_$num_upars_, " unconstrained parameter(s), but ",
length(unconstrained_variables), " were provided!", call. = FALSE)
}
private$model_methods_env_$log_prob(private$model_methods_env_$model_ptr_,
unconstrained_variables, jacobian)
}
CmdStanFit$set("public", name = "log_prob", value = log_prob)
#' Calculate the log-probability and the gradient w.r.t. each input for a
#' given vector of unconstrained parameters
#'
#' @name fit-method-grad_log_prob
#' @aliases grad_log_prob
#' @description The `$grad_log_prob()` method provides access to the Stan
#' model's `log_prob` function and its derivative.
#' @inheritParams fit-method-log_prob
#'
#' @examples
#' \dontrun{
#' fit_mcmc <- cmdstanr_example("logistic", method = "sample", force_recompile = TRUE)
#' fit_mcmc$grad_log_prob(unconstrained_variables = c(0.5, 1.2, 1.1, 2.2))
#' }
#'
#' @seealso [log_prob()], [grad_log_prob()], [constrain_variables()],
#' [unconstrain_variables()], [unconstrain_draws()], [variable_skeleton()],
#' [hessian()]
#'
grad_log_prob <- function(unconstrained_variables, jacobian = TRUE) {
self$init_model_methods()
if (length(unconstrained_variables) != private$model_methods_env_$num_upars_) {
stop("Model has ", private$model_methods_env_$num_upars_, " unconstrained parameter(s), but ",
length(unconstrained_variables), " were provided!", call. = FALSE)
}
private$model_methods_env_$grad_log_prob(private$model_methods_env_$model_ptr_,
unconstrained_variables, jacobian)
}
CmdStanFit$set("public", name = "grad_log_prob", value = grad_log_prob)
#' Calculate the log-probability , the gradient w.r.t. each input, and the hessian
#' for a given vector of unconstrained parameters
#'
#' @name fit-method-hessian
#' @aliases hessian
#' @description The `$hessian()` method provides access to the Stan model's
#' `log_prob`, its derivative, and its hessian.
#' @inheritParams fit-method-log_prob
#'
#' @examples
#' \dontrun{
#' fit_mcmc <- cmdstanr_example("logistic", method = "sample", force_recompile = TRUE)
#' # fit_mcmc$init_model_methods()
#' # fit_mcmc$hessian(unconstrained_variables = c(0.5, 1.2, 1.1, 2.2))
#' }
#'
#' @seealso [log_prob()], [grad_log_prob()], [constrain_variables()],
#' [unconstrain_variables()], [unconstrain_draws()], [variable_skeleton()],
#' [hessian()]
#'
hessian <- function(unconstrained_variables, jacobian = TRUE) {
self$init_model_methods()
if (length(unconstrained_variables) != private$model_methods_env_$num_upars_) {
stop("Model has ", private$model_methods_env_$num_upars_, " unconstrained parameter(s), but ",
length(unconstrained_variables), " were provided!", call. = FALSE)
}
private$model_methods_env_$hessian(private$model_methods_env_$model_ptr_,
unconstrained_variables, jacobian)
}
CmdStanFit$set("public", name = "hessian", value = hessian)
#' Transform a set of parameter values to the unconstrained scale
#'
#' @name fit-method-unconstrain_variables
#' @aliases unconstrain_variables
#' @description The `$unconstrain_variables()` method transforms input
#' parameters to the unconstrained scale.
#'
#' @param variables (list) A list of parameter values to transform, in the same
#' format as provided to the `init` argument of the `$sample()` method.
#'
#' @examples
#' \dontrun{
#' fit_mcmc <- cmdstanr_example("logistic", method = "sample", force_recompile = TRUE)
#' fit_mcmc$unconstrain_variables(list(alpha = 0.5, beta = c(0.7, 1.1, 0.2)))
#' }
#'
#' @seealso [log_prob()], [grad_log_prob()], [constrain_variables()],
#' [unconstrain_variables()], [unconstrain_draws()], [variable_skeleton()],
#' [hessian()]
#'
unconstrain_variables <- function(variables) {
self$init_model_methods()
model_par_names <- self$metadata()$stan_variables[self$metadata()$stan_variables != "lp__"]
prov_par_names <- names(variables)
# Ignore extraneous parameters
model_pars_only <- variables[model_par_names]
model_variables <- self$runset$args$model_variables
# If zero-length parameters are present, they will be listed in model_variables
# but not in metadata()$variables
nonzero_length_params <- names(model_variables$parameters) %in% model_par_names
model_par_names <- names(model_variables$parameters[nonzero_length_params])
model_pars_not_prov <- which(!(model_par_names %in% prov_par_names))
if (length(model_pars_not_prov) > 0) {
stop("Model parameter(s): ", paste(model_par_names[model_pars_not_prov], collapse = ","),
" not provided!", call. = FALSE)
}
variables_vector <- unlist(variables[model_par_names], recursive = TRUE)
private$model_methods_env_$unconstrain_variables(private$model_methods_env_$model_ptr_, variables_vector)
}
CmdStanFit$set("public", name = "unconstrain_variables", value = unconstrain_variables)
#' Transform all parameter draws to the unconstrained scale
#'
#' @name fit-method-unconstrain_draws
#' @aliases unconstrain_draws
#' @description The `$unconstrain_draws()` method transforms all parameter draws
#' to the unconstrained scale. The method returns a list for each chain,
#' containing the parameter values from each iteration on the unconstrained
#' scale. If called with no arguments, then the draws within the fit object
#' are unconstrained. Alternatively, either an existing draws object or a
#' character vector of paths to CSV files can be passed.
#'
#' @param files (character vector) The paths to the CmdStan CSV files. These can
#' be files generated by running CmdStanR or running CmdStan directly.
#' @param draws A `posterior::draws_*` object.
#' @param format (string) The format of the returned draws. Must be a valid
#' format from the \pkg{posterior} package.
#' @param inc_warmup (logical) Should warmup draws be included? Defaults to
#' `FALSE`.
#'
#' @examples
#' \dontrun{
#' fit_mcmc <- cmdstanr_example("logistic", method = "sample", force_recompile = TRUE)
#'
#' # Unconstrain all internal draws
#' unconstrained_internal_draws <- fit_mcmc$unconstrain_draws()
#'
#' # Unconstrain external CmdStan CSV files
#' unconstrained_csv <- fit_mcmc$unconstrain_draws(files = fit_mcmc$output_files())
#'
#' # Unconstrain existing draws object
#' unconstrained_draws <- fit_mcmc$unconstrain_draws(draws = fit_mcmc$draws())
#' }
#'
#' @seealso [log_prob()], [grad_log_prob()], [constrain_variables()],
#' [unconstrain_variables()], [unconstrain_draws()], [variable_skeleton()],
#' [hessian()]
#'
unconstrain_draws <- function(files = NULL, draws = NULL,
format = getOption("cmdstanr_draws_format", "draws_array"),
inc_warmup = FALSE) {
self$init_model_methods()
if (!(format %in% valid_draws_formats())) {
stop("Invalid draws format requested!", call. = FALSE)
}
if (!is.null(files) || !is.null(draws)) {
if (!is.null(files) && !is.null(draws)) {
stop("Either a list of CSV files or a draws object can be passed, not both",
call. = FALSE)
}
if (!is.null(files)) {
read_csv <- read_cmdstan_csv(files = files)
if (inc_warmup) {
draws <- posterior::bind_draws(read_csv$warmup_draws,
read_csv$post_warmup_draws,
along = "iteration")
} else {
draws <- read_csv$post_warmup_draws
}
} else if (!is.null(draws)) {
if (inc_warmup) {
message("'inc_warmup' cannot be used with a draws object. Ignoring.")
}
}
} else {
draws <- self$draws(inc_warmup = inc_warmup)
}
draws <- maybe_convert_draws_format(draws, "draws_matrix")
chains <- posterior::nchains(draws)
model_par_names <- self$metadata()$stan_variables[self$metadata()$stan_variables != "lp__"]
model_variables <- self$runset$args$model_variables
# If zero-length parameters are present, they will be listed in model_variables
# but not in metadata()$variables
nonzero_length_params <- names(model_variables$parameters) %in% model_par_names
# Remove zero-length parameters from model_variables, otherwise process_init
# warns about missing inputs
pars <- names(model_variables$parameters[nonzero_length_params])
draws <- posterior::subset_draws(draws, variable = pars)
unconstrained <- private$model_methods_env_$unconstrain_draws(private$model_methods_env_$model_ptr_, draws)
uncon_names <- private$model_methods_env_$unconstrained_param_names(private$model_methods_env_$model_ptr_, FALSE, FALSE)
names(unconstrained) <- repair_variable_names(uncon_names)
unconstrained$.nchains <- chains
do.call(function(...) { create_draws_format(format, ...) }, unconstrained)
}
CmdStanFit$set("public", name = "unconstrain_draws", value = unconstrain_draws)
#' Return the variable skeleton for `relist`
#'
#' @name fit-method-variable_skeleton
#' @aliases variable_skeleton
#' @description The `$variable_skeleton()` method returns the variable skeleton
#' needed by `utils::relist()` to re-structure a vector of constrained
#' parameter values to a named list.
#' @param transformed_parameters (logical) Whether to include transformed
#' parameters in the skeleton (defaults to `TRUE`).
#' @param generated_quantities (logical) Whether to include generated quantities
#' in the skeleton (defaults to `TRUE`).
#'
#' @examples
#' \dontrun{
#' fit_mcmc <- cmdstanr_example("logistic", method = "sample", force_recompile = TRUE)
#' fit_mcmc$variable_skeleton()
#' }
#'
#' @seealso [log_prob()], [grad_log_prob()], [constrain_variables()],
#' [unconstrain_variables()], [unconstrain_draws()], [variable_skeleton()],
#' [hessian()]
#'
variable_skeleton <- function(transformed_parameters = TRUE, generated_quantities = TRUE) {
self$init_model_methods()
create_skeleton(private$model_methods_env_$param_metadata_,
self$runset$args$model_variables,
transformed_parameters,
generated_quantities)
}
CmdStanFit$set("public", name = "variable_skeleton", value = variable_skeleton)
#' Transform a set of unconstrained parameter values to the constrained scale
#'
#' @name fit-method-constrain_variables
#' @aliases constrain_variables
#' @description The `$constrain_variables()` method transforms input parameters
#' to the constrained scale.
#'
#' @param unconstrained_variables (numeric) A vector of unconstrained parameters
#' to constrain.
#' @param transformed_parameters (logical) Whether to return transformed
#' parameters implied by newly-constrained parameters (defaults to TRUE).
#' @param generated_quantities (logical) Whether to return generated quantities
#' implied by newly-constrained parameters (defaults to TRUE).
#'
#' @examples
#' \dontrun{
#' fit_mcmc <- cmdstanr_example("logistic", method = "sample", force_recompile = TRUE)
#' fit_mcmc$constrain_variables(unconstrained_variables = c(0.5, 1.2, 1.1, 2.2))
#' }
#'
#' @seealso [log_prob()], [grad_log_prob()], [constrain_variables()],
#' [unconstrain_variables()], [unconstrain_draws()], [variable_skeleton()],
#' [hessian()]
#'
constrain_variables <- function(unconstrained_variables, transformed_parameters = TRUE,
generated_quantities = TRUE) {
self$init_model_methods()
skeleton <- self$variable_skeleton(transformed_parameters, generated_quantities)
if (length(unconstrained_variables) != private$model_methods_env_$num_upars_) {
stop("Model has ", private$model_methods_env_$num_upars_, " unconstrained parameter(s), but ",
length(unconstrained_variables), " were provided!", call. = FALSE)
}
cpars <- private$model_methods_env_$constrain_variables(
private$model_methods_env_$model_ptr_,
private$model_methods_env_$model_rng_,
unconstrained_variables, transformed_parameters, generated_quantities)
utils::relist(cpars, skeleton)
}
CmdStanFit$set("public", name = "constrain_variables", value = constrain_variables)
#' Extract log probability (target)
#'
#' @name fit-method-lp
#' @aliases lp lp_approx
#' @description The `$lp()` method extracts `lp__`, the total log probability
#' (`target`) accumulated in the model block of the Stan program. For
#' variational inference the log density of the variational approximation to
#' the posterior is available via the `$lp_approx()` method. For
#' Laplace approximation the unnormalized density of the approximation to
#' the posterior is available via the `$lp_approx()` method.
#'
#' See the [Increment log density and Distribution
#' Statements](https://mc-stan.org/docs/reference-manual/statements.html)
#' sections of the Stan Reference Manual for details on when normalizing
#' constants are dropped from log probability calculations.
#'
#' @section Details:
#' `lp__` is the unnormalized log density on Stan's [unconstrained
#' space](https://mc-stan.org/docs/2_23/reference-manual/variable-transforms-chapter.html).
#' This will in general be different than the unnormalized model log density
#' evaluated at a posterior draw (which is on the constrained space). `lp__` is
#' intended to diagnose sampling efficiency and evaluate approximations.
#'
#' For variational inference `lp_approx__` is the log density of the variational
#' approximation to `lp__` (also on the unconstrained space). It is exposed in
#' the variational method for performing the checks described in Yao et al.
#' (2018) and implemented in the \pkg{loo} package.
#'
#' For Laplace approximation `lp_approx__` is the unnormalized density of the
#' Laplace approximation. It can be used to perform the same checks as in the
#' case of the variational method described in Yao et al. (2018).
#'
#' @return A numeric vector with length equal to the number of (post-warmup)
#' draws or length equal to `1` for optimization.
#'
#' @references
#' Yao, Y., Vehtari, A., Simpson, D., and Gelman, A. (2018). Yes, but did it
#' work?: Evaluating variational inference. *Proceedings of the 35th
#' International Conference on Machine Learning*, PMLR 80:5581–5590.
#'
#' @seealso [`CmdStanMCMC`], [`CmdStanMLE`], [`CmdStanLaplace`], [`CmdStanVB`]
#'
#' @examples
#' \dontrun{
#' fit_mcmc <- cmdstanr_example("logistic")
#' head(fit_mcmc$lp())
#'
#' fit_mle <- cmdstanr_example("logistic", method = "optimize")
#' fit_mle$lp()
#'
#' fit_vb <- cmdstanr_example("logistic", method = "variational")
#' plot(fit_vb$lp(), fit_vb$lp_approx())
#' }
#'
lp <- function() {
lp__ <- self$draws(variables = "lp__")
lp__ <- posterior::as_draws_matrix(lp__) # if mcmc this combines all chains, otherwise does nothing
as.numeric(lp__)
}
CmdStanFit$set("public", name = "lp", value = lp)
# will be used by a subset of fit objects below
#' @rdname fit-method-lp
lp_approx <- function() {
as.numeric(self$draws()[, "lp_approx__"])
}
#' Compute a summary table of estimates and diagnostics
#'
#' @name fit-method-summary
#' @aliases summary fit-method-print print.CmdStanMCMC print.CmdStanMLE print.CmdStanVB
#' @description The `$summary()` method runs
#' [`summarise_draws()`][posterior::draws_summary] from the \pkg{posterior}
#' package and returns the output. For MCMC, only post-warmup draws are
#' included in the summary.
#'
#' There is also a `$print()` method that prints the same summary stats but
#' removes the extra formatting used for printing tibbles and returns the
#' fitted model object itself. The `$print()` method may also be faster than
#' `$summary()` because it is designed to only compute the summary statistics
#' for the variables that will actually fit in the printed output whereas
#' `$summary()` will compute them for all of the specified variables in order
#' to be able to return them to the user. See **Examples**.
#'
#' @param variables (character vector) The variables to include.
#' @param ... Optional arguments to pass to [`posterior::summarise_draws()`][posterior::draws_summary].
#'
#' @return
#' The `$summary()` method returns the tibble data frame created by
#' [`posterior::summarise_draws()`][posterior::draws_summary].
#'
#' The `$print()` method returns the fitted model object itself (invisibly),
#' which is the standard behavior for print methods in \R.
#'
#' @references
#' * Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., and Buerkner, P.-C.
#' (2021). Rank-normalization, folding, and localization: An improved R-hat
#' for assessing convergence of MCMC (with discussion).
#' *Bayesian Analysis*, 16(2), 667-718. doi:10.1214/20-BA1221.
#' * Vehtari, A. (2021). Comparison of MCMC effective sample size estimators.
#' https://avehtari.github.io/rhat_ess/ess_comparison.html
#' (for ESS diagnostics such as `ess_bulk` and `ess_tail`).
#'
#' @seealso [`CmdStanMCMC`], [`CmdStanMLE`], [`CmdStanLaplace`], [`CmdStanVB`], [`CmdStanGQ`]
#'
#' @examples
#' \dontrun{
#' fit <- cmdstanr_example("logistic")
#' fit$summary()
#' fit$print()
#' fit$print(max_rows = 2) # same as print(fit, max_rows = 2)
#'
#' # include only certain variables
#' fit$summary("beta")
#' fit$print(c("alpha", "beta[2]"))
#'
#' # include all variables but only certain summaries
#' fit$summary(NULL, c("mean", "sd"))
#'
#' # can use functions created from formulas
#' # for example, calculate Pr(beta > 0)
#' fit$summary("beta", prob_gt_0 = ~ mean(. > 0))
#'
#' # can combine user-specified functions with
#' # the default summary functions
#' fit$summary(variables = c("alpha", "beta"),
#' posterior::default_summary_measures()[1:4],
#' quantiles = ~ quantile2(., probs = c(0.025, 0.975)),
#' posterior::default_convergence_measures()
#' )
#'
#' # the functions need to calculate the appropriate
#' # value for a matrix input
#' fit$summary(variables = "alpha", dim)
#'
#' # the usual [stats::var()] is therefore not directly suitable as it
#' # will produce a covariance matrix unless the data is converted to a vector
#' fit$print(c("alpha", "beta"), var2 = ~var(as.vector(.x)))
#'
#' }
#'
summary <- function(variables = NULL, ...) {
draws <- self$draws(variables)
if (self$metadata()$method == "sample") {
summary <- posterior::summarise_draws(draws, ...)
} else {
if (!length(list(...))) {
# if user didn't supply any args use default summary measures,
# which don't include MCMC-specific things
summary <- posterior::summarise_draws(
draws,
posterior::default_summary_measures()
)
} else {
# otherwise use whatever the user specified via ...
summary <- posterior::summarise_draws(draws, ...)
}
}
if (self$metadata()$method == "optimize") {
summary <- summary[, c("variable", "mean")]
colnames(summary) <- c("variable", "estimate")
}
summary
}
CmdStanFit$set("public", name = "summary", value = summary)
#' Run CmdStan's `stansummary` and `diagnose` utilities
#'
#' @name fit-method-cmdstan_summary
#' @aliases fit-method-cmdstan_diagnose cmdstan_summary cmdstan_diagnose
#' @description Run CmdStan's `stansummary` and `diagnose` utilities. These are
#' documented in the CmdStan Guide:
#' * https://mc-stan.org/docs/cmdstan-guide/stansummary.html
#' * https://mc-stan.org/docs/cmdstan-guide/diagnose.html
#'
#' Although these methods can be used for models fit using the
#' [`$variational()`][model-method-variational] method, much of the output is
#' currently only relevant for models fit using the
#' [`$sample()`][model-method-sample] method.
#'
#' See the [$summary()][fit-method-summary] for computing similar summaries in
#' R rather than calling CmdStan's utilites.
#'
#' @param flags An optional character vector of flags (e.g.
#' `flags = c("--sig_figs=1")`).
#'
#' @seealso [`CmdStanMCMC`], [fit-method-summary]
#'
#' @examples
#' \dontrun{
#' fit <- cmdstanr_example("logistic")
#' fit$cmdstan_diagnose()
#' fit$cmdstan_summary()
#' }
#'
cmdstan_summary <- function(flags = NULL) {
self$runset$run_cmdstan_tool("stansummary", flags = flags)
}
CmdStanFit$set("public", name = "cmdstan_summary", value = cmdstan_summary)
#' @rdname fit-method-cmdstan_summary
cmdstan_diagnose <- function() {
self$runset$run_cmdstan_tool("diagnose")
}
CmdStanFit$set("public", name = "cmdstan_diagnose", value = cmdstan_diagnose)
#' Save output and data files
#'
#' @name fit-method-save_output_files
#' @aliases fit-method-save_data_file fit-method-save_latent_dynamics_files
#' fit-method-save_profile_files fit-method-output_files fit-method-data_file
#' fit-method-latent_dynamics_files fit-method-profile_files
#' fit-method-save_config_files fit-method-save_metric_files save_output_files
#' save_data_file save_latent_dynamics_files save_profile_files
#' save_config_files save_metric_files output_files data_file
#' latent_dynamics_files profile_files config_files metric_files
#'
#' @description All fitted model objects have methods for saving (moving to a
#' specified location) the files created by CmdStanR to hold CmdStan output
#' csv files and input data files. These methods move the files from their
#' current location (possibly the temporary directory) to a user-specified
#' location. __The paths stored in the fitted model object will also be
#' updated to point to the new file locations.__
#'
#' The versions without the `save_` prefix (e.g., `$output_files()`) return
#' the current file paths without moving any files.
#'
#' @param dir (string) Path to directory where the files should be saved.
#' @param basename (string) Base filename to use. See __Details__.
#' @param timestamp (logical) Should a timestamp be added to the file name(s)?
#' Defaults to `TRUE`. See __Details__.
#' @param random (logical) Should random alphanumeric characters be added to the
#' end of the file name(s)? Defaults to `TRUE`. See __Details__.
#'
#' @section Details:
#' For `$save_output_files()` the files moved to `dir` will have names of
#' the form `basename-timestamp-id-random`, where
#' * `basename` is the user's provided `basename` argument;
#' * `timestamp` is of the form `format(Sys.time(), "%Y%m%d%H%M")`;
#' * `id` is the MCMC chain id (or `1` for non MCMC);
#' * `random` contains six random alphanumeric characters;
#'
#' For `$save_latent_dynamics_files()` everything is the same as for
#' `$save_output_files()` except `"-diagnostic-"` is included in the new
#' file name after `basename`.
#'
#' For `$save_profile_files()` everything is the same as for
#' `$save_output_files()` except `"-profile-"` is included in the new
#' file name after `basename`.
#'
#' For `$save_metric_files()` everything is the same as for
#' `$save_output_files()` except `"-metric-"` is included in the new
#' file name after `basename`.
#'
#' For `$save_config_files()` everything is the same as for
#' `$save_output_files()` except `"-config-"` is included in the new
#' file name after `basename`.
#'
#' For `$save_data_file()` no `id` is included in the file name because even
#' with multiple MCMC chains the data file is the same.
#'
#' @return
#' The `$save_*` methods print a message with the new file paths and (invisibly)
#' return a character vector of the new paths (or `NA` for any that couldn't be
#' copied). They also have the side effect of setting the internal paths in the
#' fitted model object to the new paths.
#'
#' The methods _without_ the `save_` prefix return character vectors of file
#' paths without moving any files.
#'
#' @seealso [`CmdStanMCMC`], [`CmdStanMLE`], [`CmdStanVB`], [`CmdStanGQ`]
#'
#' @examples
#' \dontrun{
#' fit <- cmdstanr_example()
#' fit$output_files()
#' fit$data_file()
#'
#' # just using tempdir for the example
#' my_dir <- tempdir()
#' fit$save_output_files(dir = my_dir, basename = "banana")
#' fit$save_output_files(dir = my_dir, basename = "tomato", timestamp = FALSE)
#' fit$save_output_files(dir = my_dir, basename = "lettuce", timestamp = FALSE, random = FALSE)
#' }
#'
save_output_files <- function(dir = ".",
basename = NULL,
timestamp = TRUE,
random = TRUE) {
self$runset$save_output_files(dir, basename, timestamp, random)
}
CmdStanFit$set("public", name = "save_output_files", value = save_output_files)
#' @rdname fit-method-save_output_files
save_latent_dynamics_files <- function(dir = ".",
basename = NULL,
timestamp = TRUE,
random = TRUE) {