-
Notifications
You must be signed in to change notification settings - Fork 3
/
utility_functions.R
2144 lines (1982 loc) · 93.9 KB
/
utility_functions.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
# Methods for bayesianVARs_bvar objects -----------------------------------
#' Pretty printing of a bvar object
#'
#' @param x Object of class `bayesianVARs_bvar`, usually resulting from a call
#' of [`bvar()`].
#' @param ... Ignored.
#'
#' @return Returns \code{x} invisibly.
#'
#' @export
#'
#' @examples
#' # Access a subset of the usmacro_growth dataset
#' data <- usmacro_growth[,c("GDPC1", "CPIAUCSL", "FEDFUNDS")]
#'
#' # Estimate a model
#' mod <- bvar(data, sv_keep = "all", quiet = TRUE)
#'
#' # Print model
#' mod
#'
print.bayesianVARs_bvar <- function(x, ...) {
M <- ncol(x$Y)
Tobs <- nrow(x$Y)
Traw <- nrow(x$Yraw)
if(inherits(x, "bayesianVARs_bvar_stable")){
cat(paste("\nFitted bayesianVARs_bvar_stable object with\n",
" -", formatC(dim(x$PHI)[3], width = 7), "remaining stable draws\n"))
}
cat(paste("\nFitted bayesianVARs_bvar object with\n",
" -", formatC(M, width = 7), "series\n",
" -", formatC(x$lags, width = 7), "lag(s)\n",
" -", formatC(Tobs, width = 7), "used observations\n",
" -", formatC(Traw, width = 7), "total observations\n",
" -", formatC(x$config$draws, width = 7), "MCMC draws\n",
" -", formatC(x$config$thin, width = 7), "thinning\n",
" -", formatC(x$config$burnin, width = 7), "burn-in\n\n"))
invisible(x)
}
#' Summary method for bayesianVARs_bvar objects
#'
#' Summary method for `bayesianVARs_bvar` objects.
#'
#' @param object A `bayesianVARs_bvar` object obtained via [`bvar()`].
#' @param quantiles numeric vector which quantiles to compute.
#' @param ... Currently ignored!
#'
#' @return An object of type `summary.bayesianVARs_bvar`.
#' @export
#'
#' @examples
#' # Access a subset of the usmacro_growth dataset
#' data <- usmacro_growth[,c("GDPC1", "CPIAUCSL", "FEDFUNDS")]
#'
#' # Estimate model
#' mod <- bvar(data, quiet = TRUE)
#'
#' # Summary
#' sum <- summary(mod)
summary.bayesianVARs_bvar <- function(object, quantiles = c(0.025, 0.25, 0.5, 0.75, 0.975),...){
PHImedian <- apply(object$PHI, 1:2, stats::median)
PHIquantiles <- apply(object$PHI, 1:2, stats::quantile, quantiles)
PHIiqr <- apply(object$PHI, 1:2, stats::IQR)
if(object$sigma_type == "cholesky"){
Umedian <- Uiqr <- diag(1, nrow = ncol(object$Y))
colnames(Umedian) <- rownames(Umedian) <-
colnames(Uiqr) <- rownames(Uiqr) <- colnames(object$Y)
Umedian[upper.tri(Umedian)] <- apply(object$U, 1, stats::median)
Uquantiles <- apply(object$U, 1, stats::quantile, quantiles)
Uiqr[upper.tri(Uiqr)] <- apply(object$U, 1, stats::IQR)
}
out <- list(PHImedian = PHImedian,
PHIquantiles = PHIquantiles,
PHIiqr = PHIiqr
)
if(object$sigma_type == "cholesky"){
out$Umedian <- Umedian
out$Uquantiles <- Uquantiles
out$Uiqr <- Uiqr
}
out$sigma_type <- object$sigma_type
class(out) <- "summary.bayesianVARs_bvar"
out
}
#' Print method for summary.bayesianVARs_bvar objects
#'
#' Print method for `summary.bayesianVARs_bvar` objects.
#'
#' @param x A `summary.bayesianVARs_bvar` object obtained via
#' [`summary.bayesianVARs_bvar()`].
#' @param ... Currently ignored!
#'
#' @return Returns `x` invisibly!
#' @export
#'
#' @examples
#' # Access a subset of the usmacro_growth dataset
#' data <- usmacro_growth[,c("GDPC1", "CPIAUCSL", "FEDFUNDS")]
#'
#' # Estimate model
#' mod <- bvar(data, quiet = TRUE)
#'
#' # Print summary
#' summary(mod)
print.summary.bayesianVARs_bvar <- function(x, ...){
digits <- max(3, getOption("digits") - 3)
cat("\nPosterior median of reduced-form coefficients:\n")
print(x$PHImedian, digits = digits)
cat("\nPosterior interquartile range of of reduced-form coefficients:\n")
print(x$PHIiqr, digits = digits)
if(x$sigma_type == "cholesky"){
cat("\nPosterior median of contemporaneous coefficients:\n")
print(as.table(x$Umedian - diag(nrow(x$Umedian))), digits = digits, zero.print = "-")
cat("\nPosterior interquartile range of contemporaneous coefficients:\n")
print(as.table(x$Uiqr- diag(nrow(x$Uiqr))), digits = digits, zero.print = "-")
}
invisible(x)
}
#' @name coef
#' @title Extract VAR coefficients
#' @description Extracts posterior draws of the VAR coefficients from a VAR
#' model estimated with [`bvar()`].
#'
#' @param object A `bayesianVARs_bvar` object obtained from [`bvar()`].
#' @param ... Currently ignored.
#'
#' @return Returns a numeric array of dimension \eqn{M \times K \times draws},
#' where M is the number of time-series, K is the number of covariates per
#' equation (including the intercept) and draws is the number of stored
#' posterior draws.
#' @seealso [`summary.bayesianVARs_draws()`], [`vcov.bayesianVARs_bvar()`].
#' @export
#'
#' @examples
#' # Access a subset of the usmacro_growth dataset
#' data <- usmacro_growth[,c("GDPC1", "CPIAUCSL", "FEDFUNDS")]
#'
#' # Estimate a model
#' mod <- bvar(data, sv_keep = "all", quiet = TRUE)
#'
#' # Extract posterior draws of VAR coefficients
#' bvar_coefs <- coef(mod)
coef.bayesianVARs_bvar <- function(object, ...){
ret <- object$PHI
class(ret) <- c("bayesianVARs_coef", "bayesianVARs_draws")
ret
}
#' Extract posterior draws of the (time-varying) variance-covariance matrix for
#' a VAR model
#'
#' Returns the posterior draws of the possibly time-varying variance-covariance
#' matrix of a VAR estimated via [`bvar()`]. Returns the full paths if
#' `sv_keep="all"` when calling [`bvar()`]. Otherwise, the draws of the
#' variance-covariance matrix for the last observation are returned, only.
#'
#' @param object An object of class `bayesianVARs_bvar` obtained via [`bvar()`].
#' @param t Vector indicating which points in time should be extracted, defaults
#' to all.
#' @param ... Currently ignored.
#'
#' @return An array of class `bayesianVARs_draws` of dimension \eqn{T \times M
#' \times M \times draws}, where \eqn{T} is the number of observations,
#' \eqn{M} the number of time-series and \eqn{draws} the number of stored
#' posterior draws.
#' @seealso [`summary.bayesianVARs_draws`], [`coef.bayesianVARs_bvar()`].
#' @export
#'
#' @examples
#' # Access a subset of the usmacro_growth dataset
#' data <- usmacro_growth[,c("GDPC1", "CPIAUCSL", "FEDFUNDS")]
#' # Estimate a model
#' mod <- bvar(data, sv_keep = "all", quiet = TRUE)
#'
#' # Extract posterior draws of the variance-covariance matrix
#' bvar_vcov <- vcov(mod)
vcov.bayesianVARs_bvar <- function(object, t = seq_len(nrow(object$logvar)), ...){
M <- ncol(object$Y)
factors <- dim(object$facload)[2]
Tobs <- length(t)
nsave <- dim(object$PHI)[3]
dates <- t
if(!is.null(rownames(object$Y)) & !is.null(dates)){
dates <- tryCatch(as.Date(rownames(object$Yraw)[dates]),
error = function(e) dates)
}
out <- vcov_cpp(object$sigma_type == "factor",
object$facload,
object$logvar[t,,,drop=FALSE],
object$U,
M,
factors)
out <- array(out, c(Tobs, M, M, nsave))
dimnames(out) <- list(as.character(dates), colnames(object$Y),
colnames(object$Y), NULL)
class(out) <- "bayesianVARs_draws"
out
}
#' Summary statistics for bayesianVARs posterior draws.
#'
#' @param object An object of class `bayesianVARs_draws` usually obtained through
#' extractors like [`coef.bayesianVARs_bvar()`] and
#' [`vcov.bayesianVARs_bvar()`].
#' @param quantiles A vector of quantiles to evaluate.
#' @param ... Currently ignored.
#'
#' @return A list object of class `bayesianVARs_draws_summary` holding
#' * `mean`: Vector or matrix containing the posterior mean.
#' * `sd`: Vector or matrix containing the posterior standard deviation .
#' * `quantiles`: Array containing the posterior quantiles.
#' @seealso Available extractors: [`coef.bayesianVARs_bvar()`],
#' [`vcov.bayesianVARs_bvar()`].
#' @export
#'
#' @examples
#'
#' # Access a subset of the usmacro_growth dataset
#' data <- usmacro_growth[,c("GDPC1", "CPIAUCSL", "FEDFUNDS")]
#' # Estimate a model
#' mod <- bvar(data, sv_keep = "all", quiet = TRUE)
#'
#' # Extract posterior draws of VAR coefficients
#' bvar_coefs <- coef(mod)
#'
#' # Compute summary statistics
#' summary_stats <- summary(bvar_coefs)
#'
#' # Compute summary statistics of VAR coefficients without using coef()
#' summary_stats <- summary(mod$PHI)
#'
#' # Test which list elements of 'mod' are of class 'bayesianVARs_draws'.
#' names(mod)[sapply(names(mod), function(x) inherits(mod[[x]], "bayesianVARs_draws"))]
#'
summary.bayesianVARs_draws <- function(object, quantiles = c(0.25, 0.5, 0.75),
...){
dim_object <- dim(object)
dim_length <- length(dim_object)
object_mean <- apply(object, 1:(dim_length-1), mean)
object_sd <- apply(object, 1:(dim_length-1), sd)
object_quantiles <- apply(object, 1:(dim_length-1), quantile, quantiles)
out <- list(
mean = object_mean,
sd = object_sd,
quantiles = object_quantiles
)
class(out) <- "bayesianVARs_draws_summary"
return(out)
}
#' Simulate fitted/predicted historical values for an estimated VAR model
#'
#' Simulates the fitted/predicted (in-sample) values for an estimated VAR model.
#'
#' @param object A `bayesianVARs_bvar` object estimated via [bvar()].
#' @param error_term logical indicating whether to include the error term or
#' not.
#' @param ... Currently ignored.
#'
#' @return An object of class `bayesianVARs_fitted`.
#' @export
#'
#' @examples
#' # Access a subset of the usmacro_growth dataset
#' data <- usmacro_growth[,c("GDPC1", "CPIAUCSL", "FEDFUNDS")]
#'
#' # Estimate a model
#' mod <- bvar(data, sv_keep = "all", quiet = TRUE)
#'
#' # Simulate predicted historical values including the error term.
#' pred <- fitted(mod, error_term = TRUE)
#'
#' # Simulate fitted historical values not including the error term.
#' fit <- fitted(mod, error_term = FALSE)
#'
#' # Visualize
#' plot(pred)
#' plot(fit)
fitted.bayesianVARs_bvar <- function(object, error_term = TRUE, ...){
if(dim(object$logvar)[1] != nrow(object$Y) & error_term){
warning("Setting 'error_term=FALSE'! To calculate predicted historical
values including the error term, the full path of logvariances is needed,
i.e. set 'sv_keep='all'' when calling bvar()!")
error_term <- FALSE
}
ret <- insample(object$X,
object$PHI,
object$U,
object$facload,
object$logvar,
error_term,
object$sigma_type == "factor")
colnames(ret) <- colnames(object$Y)
rownames(ret) <- rownames(object$Y)
out <- list(
fitted = ret,
Yraw = object$Yraw
)
class(out) <- "bayesianVARs_fitted"
out
}
# Functions for prior configuration ---------------------------------------
#'Specify prior on Sigma
#'
#'Configures prior on the variance-covariance of the VAR.
#'
#'\code{bvar} offers two different specifications for the errors: The user can
#'choose between a factor stochastic volatility structure or a cholesky
#'stochastic volatility structure. In both cases the disturbances
#'\eqn{\boldsymbol{\epsilon}_t} are assumed to follow a \eqn{M}-dimensional
#'multivariate normal distribution with zero mean and variance-covariance matrix
#'\eqn{\boldsymbol{\Sigma}_t}. In case of the cholesky specification
#'\eqn{\boldsymbol{\Sigma}_t = \boldsymbol{U}^{\prime -1} \boldsymbol{D}_t
#'\boldsymbol{U}^{-1}}, where \eqn{\boldsymbol{U}^{-1}} is upper unitriangular (with ones on
#'the diagonal). The diagonal matrix \eqn{\boldsymbol{D}_t} depends upon latent
#'log-variances, i.e. \eqn{\boldsymbol{D}_t=diag(exp(h_{1t}),\dots, exp(h_{Mt})}. The
#'log-variances follow a priori independent autoregressive processes
#'\eqn{h_{it}\sim N(\mu_i + \phi_i(h_{i,t-1}-\mu_i),\sigma_i^2)} for
#'\eqn{i=1,\dots,M}. In case of the factor structure,
#'\eqn{\boldsymbol{\Sigma}_t = \boldsymbol{\Lambda} \boldsymbol{V}_t \boldsymbol{\Lambda}^\prime +
#'\boldsymbol{G}_t}. The diagonal matrices \eqn{\boldsymbol{V}_t} and
#'\eqn{\boldsymbol{G}_t} depend upon latent log-variances, i.e.
#'\eqn{\boldsymbol{G}_t=diag(exp(h_{1t}),\dots, exp(h_{Mt})} and
#'\eqn{\boldsymbol{V}_t=diag(exp(h_{M+1,t}),\dots, exp(h_{M+r,t})}. The log-variances
#'follow a priori independent autoregressive processes \eqn{h_{it}\sim N(\mu_i +
#'\phi_i(h_{i,t-1}-\mu_i),\sigma_i^2)} for \eqn{i=1,\dots,M} and
#'\eqn{h_{M+j,t}\sim N(\phi_ih_{M+j,t-1},\sigma_{M+j}^2)} for \eqn{j=1,\dots,r}.
#'
#'@param data Optional. Data matrix (can be a time series object). Each of
#' \eqn{M} columns is assumed to contain a single time-series of length
#' \eqn{T}.
#'@param M positive integer indicating the number of time-series of the VAR.
#'@param type character, one of `"factor"` (the default) or `"cholesky"`,
#' indicating which decomposition to be applied to the covariance-matrix.
#'@param factor_factors Number of latent factors to be estimated. Only required
#' if `type="factor"`.
#'@param factor_restrict Either "upper" or "none", indicating whether the factor
#' loadings matrix should be restricted to have zeros above the diagonal
#' ("upper") or whether all elements should be estimated from the data
#' ("none"). Setting \code{restrict} to "upper" often stabilizes MCMC
#' estimation and can be important for identifying the factor loadings matrix,
#' however, it generally is a strong prior assumption. Setting \code{restrict}
#' to "none" is usually the preferred option if identification of the factor
#' loadings matrix is of less concern but covariance estimation or prediction
#' is the goal. Only required if `type="factor"`.
#'@param factor_priorfacloadtype Can be \code{"normal"}, \code{"rowwiseng"},
#' \code{"colwiseng"}. Only required if `type="factor"`.
#' \describe{
#' \item{\code{"normal"}: }{Normal prior. The value of \code{priorfacload}
#' is interpreted as the standard deviations of the
#' Gaussian prior distributions for the factor loadings.}
#' \item{\code{"rowwiseng"}: }{Row-wise Normal-Gamma prior. The value of \code{priorfacload}
#' is interpreted as the shrinkage parameter \code{a}.}
#' \item{\code{"colwiseng"}: }{Column-wise Normal-Gamma prior. The value of \code{priorfacload}
#' is interpreted as the shrinkage parameter \code{a}.}
#' }
#' For details please see Kastner (2019).
#'@param factor_priorfacload Either a matrix of dimensions \code{M} times
#' \code{factor_factors} with positive elements or a single number (which will
#' be recycled accordingly). Only required if `type="factor"`. The meaning of
#' \code{factor_priorfacload} depends on the setting of
#' \code{factor_priorfacloadtype} and is explained there.
#'@param factor_facloadtol Minimum number that the absolute value of a factor
#' loadings draw can take. Prevents numerical issues that can appear when
#' strong shrinkage is enforced if chosen to be greater than zero. Only
#' required if `type="factor"`.
#'@param factor_priorng Two-element vector with positive entries indicating the
#' Normal-Gamma prior's hyperhyperparameters \code{c} and \code{d} (cf. Kastner
#' (2019)). Only required if `type="factor"`.
#'@param factor_priormu Vector of length 2 denoting prior mean and standard
#' deviation for unconditional levels of the idiosyncratic log variance
#' processes. Only required if `type="factor"`.
#'@param factor_priorphiidi Vector of length 2, indicating the shape parameters
#' for the Beta prior distributions of the transformed parameters
#' \code{(phi+1)/2}, where \code{phi} denotes the persistence of the
#' idiosyncratic log variances. Only required if `type="factor"`.
#'@param factor_priorphifac Vector of length 2, indicating the shape parameters
#' for the Beta prior distributions of the transformed parameters
#' \code{(phi+1)/2}, where \code{phi} denotes the persistence of the factor log
#' variances. Only required if `type="factor"`.
#'@param factor_priorsigmaidi Vector of length \code{M} containing the prior
#' volatilities of log variances. If \code{factor_priorsigmaidi} has exactly
#' one element, it will be recycled for all idiosyncratic log variances. Only
#' required if `type="factor"`.
#'@param factor_priorsigmafac Vector of length \code{factor_factors} containing
#' the prior volatilities of log variances. If \code{factor_priorsigmafac} has
#' exactly one element, it will be recycled for all factor log variances. Only
#' required if `type="factor"`.
#'@param factor_priorh0idi Vector of length 1 or \code{M}, containing
#' information about the Gaussian prior for the initial idiosyncratic log
#' variances. Only required if `type="factor"`. If an element of
#' \code{factor_priorh0idi} is a nonnegative number, the conditional prior of
#' the corresponding initial log variance h0 is assumed to be Gaussian with
#' mean 0 and standard deviation \code{factor_priorh0idi} times \eqn{sigma}. If
#' an element of \code{factor_priorh0idi} is the string 'stationary', the prior
#' of the corresponding initial log volatility is taken to be from the
#' stationary distribution, i.e. h0 is assumed to be Gaussian with mean 0 and
#' variance \eqn{sigma^2/(1-phi^2)}.
#'@param factor_priorh0fac Vector of length 1 or \code{factor_factors},
#' containing information about the Gaussian prior for the initial factor log
#' variances. Only required if `type="factor"`. If an element of
#' \code{factor_priorh0fac} is a nonnegative number, the conditional prior of
#' the corresponding initial log variance h0 is assumed to be Gaussian with
#' mean 0 and standard deviation \code{factor_priorh0fac} times \eqn{sigma}. If
#' an element of \code{factor_priorh0fac} is the string 'stationary', the prior
#' of the corresponding initial log volatility is taken to be from the
#' stationary distribution, i.e. h0 is assumed to be Gaussian with mean 0 and
#' variance \eqn{sigma^2/(1-phi^2)}.
#'@param factor_heteroskedastic Vector of length 1, 2, or \code{M +
#' factor_factors}, containing logical values indicating whether time-varying
#' (\code{factor_heteroskedastic = TRUE}) or constant (\code{factor_heteroskedastic =
#' FALSE}) variance should be estimated. If \code{factor_heteroskedastic} is of
#' length 2 it will be recycled accordingly, whereby the first element is used
#' for all idiosyncratic variances and the second element is used for all
#' factor variances. Only required if `type="factor"`.
#'@param factor_priorhomoskedastic Only used if at least one element of
#' \code{factor_heteroskedastic} is set to \code{FALSE}. In that case,
#' \code{factor_priorhomoskedastic} must be a matrix with positive entries and
#' dimension c(M, 2). Values in column 1 will be interpreted as the shape and
#' values in column 2 will be interpreted as the rate parameter of the
#' corresponding inverse gamma prior distribution of the idiosyncratic
#' variances. Only required if `type="factor"`.
#'@param factor_interweaving The following values for interweaving the factor
#' loadings are accepted (Only required if `type="factor"`):
#' \describe{
#' \item{0: }{No interweaving.}
#' \item{1: }{Shallow interweaving through the diagonal entries.}
#' \item{2: }{Deep interweaving through the diagonal entries.}
#' \item{3: }{Shallow interweaving through the largest absolute entries in each column.}
#' \item{4: }{Deep interweaving through the largest absolute entries in each column.}
#' }
#' For details please see Kastner et al. (2017). A value of 4 is the highly
#' recommended default.
#'@param cholesky_U_prior character, one of \code{"HS"}, \code{"R2D2"}, `"NG"`,
#' \code{"DL"}, \code{"SSVS"}, \code{"HMP"} or \code{"normal"}. Only required
#' if `type="cholesky"`.
#'@param cholesky_U_tol Minimum number that the absolute value of an free
#' off-diagonal element of an \eqn{U}-draw can take. Prevents numerical issues
#' that can appear when strong shrinkage is enforced if chosen to be greater
#' than zero. Only required if `type="cholesky"`.
#'@param cholesky_heteroscedastic single logical indicating whether time-varying
#' (\code{cholesky_heteroscedastic = TRUE}) or constant
#' (\code{cholesky_heteroscedastic = FALSE}) variance should be estimated. Only
#' required if `type="cholesky"`.
#'@param cholesky_priormu Vector of length 2 denoting prior mean and standard
#' deviation for unconditional levels of the log variance processes. Only
#' required if `type="cholesky"`.
#'@param cholesky_priorphi Vector of length 2, indicating the shape parameters
#' for the Beta prior distributions of the transformed parameters
#' \code{(phi+1)/2}, where \code{phi} denotes the persistence of the log
#' variances. Only required if `type="cholesky"`.
#'@param cholesky_priorsigma2 Vector of length 2, indicating the shape and the
#' rate for the Gamma prior distributions on the variance of the log variance
#' processes. (Currently only one global setting for all \eqn{M} processes is
#' supported). Only required if `type="cholesky"`.
#'@param cholesky_priorh0 Vector of length 1 or \code{M}, containing information
#' about the Gaussian prior for the initial idiosyncratic log variances. Only
#' required if `type="cholesky"`. If an element of \code{cholesky_priorh0} is a
#' nonnegative number, the conditional prior of the corresponding initial log
#' variance h0 is assumed to be Gaussian with mean 0 and standard deviation
#' \code{cholesky_priorh0} times \eqn{sigma}. If an element of
#' \code{cholesky_priorh0} is the string 'stationary', the prior of the
#' corresponding initial log volatility is taken to be from the stationary
#' distribution, i.e. h0 is assumed to be Gaussian with mean 0 and variance
#' \eqn{sigma^2/(1-phi^2)}.
#'@param cholesky_priorhomoscedastic Only used if
#' \code{cholesky_heteroscedastic=FALSE}. In that case,
#' \code{cholesky_priorhomoscedastic} must be a matrix with positive entries
#' and dimension c(M, 2). Values in column 1 will be interpreted as the shape
#' and values in column 2 will be interpreted as the scale parameter of the
#' corresponding inverse gamma prior distribution of the variances. Only
#' required if `type="cholesky"`.
#'@param cholesky_DL_a (Single) positive real number. The value is interpreted
#' as the concentration parameter for the local scales. Smaller values enforce
#' heavier shrinkage. A matrix of dimension `c(s,2)` specifies a discrete
#' hyperprior, where the first column contains s support points and the second
#' column contains the associated prior probabilities. `cholesky_DL_a` has only
#' to be specified if `cholesky_U_prior="DL"`.
#'@param cholesky_DL_tol Minimum number that a parameter draw of one of the
#' shrinking parameters of the Dirichlet Laplace prior can take. Prevents
#' numerical issues that can appear when strong shrinkage is enforced if chosen
#' to be greater than zero. `DL_tol` has only to be specified if
#' `cholesky_U_prior="DL"`.
#'@param cholesky_R2D2_a (Single) positive real number. The value is interpreted
#' as the concentration parameter for the local scales. Smaller values enforce
#' heavier shrinkage. A matrix of dimension `c(s,2)` specifies a discrete
#' hyperprior, where the first column contains s support points and the second
#' column contains the associated prior probabilities. cholesky_R2D2_a has only
#' to be specified if `cholesky_U_prior="R2D2"`.
#'@param cholesky_R2D2_b single positive number, where greater values indicate
#' heavier regularization. \code{cholesky_R2D2_b} has only to be specified if
#' \code{cholesky_U_prior="R2D2"}.
#'@param cholesky_R2D2_tol Minimum number that a parameter draw of one of the
#' shrinking parameters of the R2D2 prior can take. Prevents numerical issues
#' that can appear when strong shrinkage is enforced if chosen to be greater
#' than zero. `cholesky_R2D2_tol` has only to be specified if
#' `cholesky_U_prior="R2D2"`.
#'@param cholesky_NG_a (Single) positive real number. The value is interpreted
#' as the concentration parameter for the local scales. Smaller values enforce
#' heavier shrinkage. A matrix of dimension `c(s,2)` specifies a discrete
#' hyperprior, where the first column contains s support points and the second
#' column contains the associated prior probabilities. `cholesky_NG_a` has only
#' to be specified if `cholesky_U_prior="NG"`.
#'@param cholesky_NG_b (Single) positive real number. The value indicates the
#' shape parameter of the inverse gamma prior on the global scales.
#' `cholesky_NG_b` has only to be specified if `cholesky_U_prior="NG"`.
#'@param cholesky_NG_c (Single) positive real number. The value indicates the
#' scale parameter of the inverse gamma prior on the global scales.
#' Expert option would be to set the scale parameter proportional to NG_a. E.g.
#' in the case where a discrete hyperprior for NG_a is chosen, a desired
#' proportion of let's say 0.2 is achieved by setting NG_c="0.2a" (character
#' input!). `cholesky_NG_c` has only to be specified if
#' `cholesky_U_prior="NG"`.
#'@param cholesky_NG_tol Minimum number that a parameter draw of one of the
#' shrinking parameters of the normal-gamma prior can take. Prevents numerical
#' issues that can appear when strong shrinkage is enforced if chosen to be
#' greater than zero. `cholesky_NG_tol` has only to be specified if
#' `cholesky_U_prior="NG"`.
#'@param cholesky_SSVS_c0 single positive number indicating the (unscaled)
#' standard deviation of the spike component. \code{cholesky_SSVS_c0} has only
#' to be specified if \code{choleksy_U_prior="SSVS"}.
#' It should be that \eqn{SSVS_{c0}
#' \ll SSVS_{c1}}!
#'@param cholesky_SSVS_c1 single positive number indicating the (unscaled)
#' standard deviation of the slab component. \code{cholesky_SSVS_c1} has only
#' to be specified if \code{choleksy_U_prior="SSVS"}. It should be that
#' \eqn{SSVS_{c0} \ll SSVS_{c1}}!
#'@param cholesky_SSVS_p Either a single positive number in the range `(0,1)`
#' indicating the (fixed) prior inclusion probability of each coefficient. Or
#' numeric vector of length 2 with positive entries indicating the shape
#' parameters of the Beta distribution. In that case a Beta hyperprior is
#' placed on the prior inclusion probability. `cholesky_SSVS_p` has only to be
#' specified if \code{choleksy_U_prior="SSVS"}.
#'@param cholesky_HMP_lambda3 numeric vector of length 2. Both entries must be
#' positive. The first indicates the shape and the second the rate of the Gamma
#' hyperprior on the contemporaneous coefficients. `cholesky_HMP_lambda3` has
#' only to be specified if \code{choleksy_U_prior="HMP"}.
#'@param cholesky_normal_sds numeric vector of length \eqn{\frac{M^2-M}{2}},
#' indicating the prior variances for the free off-diagonal elements in
#' \eqn{U}. A single number will be recycled accordingly! Must be positive.
#' `cholesky_normal_sds` has only to be specified if
#' `choleksy_U_prior="normal"`.
#'@param expert_sv_offset ... Do not use!
#'@param quiet logical indicating whether informative output should be omitted.
#'@param ... Do not use!
#'
#'@seealso [specify_prior_phi()].
#'
#'@return Object of class `bayesianVARs_prior_sigma`.
#'@export
#'
#'@references Kastner, G. (2019). Sparse Bayesian Time-Varying Covariance
#' Estimation in Many Dimensions \emph{Journal of Econometrics}, \bold{210}(1),
#' 98--115, \doi{10.1016/j.jeconom.2018.11.007}
#'
#'@references Kastner, G., Frühwirth-Schnatter, S., and Lopes, H.F. (2017).
#' Efficient Bayesian Inference for Multivariate Factor Stochastic Volatility
#' Models. \emph{Journal of Computational and Graphical Statistics},
#' \bold{26}(4), 905--917, \doi{10.1080/10618600.2017.1322091}.
#'
#' @examples
#' # Access a subset of the usmacro_growth dataset
#' data <- usmacro_growth[,c("GDPC1", "CPIAUCSL", "FEDFUNDS")]
#'
#' # examples with stochastic volatility (heteroscedasticity) -----------------
#' # factor-decomposition with 2 factors and colwise normal-gamma prior on the loadings
#' sigma_factor_cng_sv <- specify_prior_sigma(data = data, type = "factor",
#' factor_factors = 2L, factor_priorfacloadtype = "colwiseng", factor_heteroskedastic = TRUE)
#'
#' # cholesky-decomposition with Dirichlet-Laplace prior on U
#' sigma_cholesky_dl_sv <- specify_prior_sigma(data = data, type = "cholesky",
#' cholesky_U_prior = "DL", cholesky_DL_a = 0.5, cholesky_heteroscedastic = TRUE)
#'
#' # examples without stochastic volatility (homoscedasticity) ----------------
#' # factor-decomposition with 2 factors and colwise normal-gamma prior on the loadings
#' sigma_factor_cng <- specify_prior_sigma(data = data, type = "factor",
#' factor_factors = 2L, factor_priorfacloadtype = "colwiseng",
#' factor_heteroskedastic = FALSE, factor_priorhomoskedastic = matrix(c(0.5,0.5),
#' ncol(data), 2))
#'
#' # cholesky-decomposition with Horseshoe prior on U
#' sigma_cholesky_dl <- specify_prior_sigma(data = data, type = "cholesky",
#' cholesky_U_prior = "HS", cholesky_heteroscedastic = FALSE)
#'
#'\donttest{
#' # Estimate model with your prior configuration of choice
#' mod <- bvar(data, prior_sigma = sigma_factor_cng_sv, quiet = TRUE)
#'}
specify_prior_sigma <- function(data=NULL,
M = ncol(data),
type = c("factor", "cholesky"),
factor_factors = 1L,
factor_restrict = c("none", "upper"),
factor_priorfacloadtype = c("rowwiseng", "colwiseng", "normal"),
factor_priorfacload = 0.1,
factor_facloadtol = 1e-18,
factor_priorng = c(1,1),
factor_priormu = c(0,10),
factor_priorphiidi = c(10, 3),
factor_priorphifac = c(10, 3),
factor_priorsigmaidi = 1,
factor_priorsigmafac = 1,
factor_priorh0idi = "stationary",
factor_priorh0fac = "stationary",
factor_heteroskedastic = TRUE,
factor_priorhomoskedastic = NA,
factor_interweaving = 4,
cholesky_U_prior = c("HS", "DL", "R2D2", "NG", "SSVS", "normal", "HMP"),
cholesky_U_tol = 1e-18,
cholesky_heteroscedastic = TRUE,
cholesky_priormu = c(0,100),
cholesky_priorphi = c(20, 1.5),
cholesky_priorsigma2 = c(0.5, 0.5),
cholesky_priorh0 = "stationary",
cholesky_priorhomoscedastic = as.numeric(NA),
cholesky_DL_a = "1/n",
cholesky_DL_tol = 0,
cholesky_R2D2_a =0.4,
cholesky_R2D2_b = 0.5,
cholesky_R2D2_tol=0,
cholesky_NG_a = .5,
cholesky_NG_b = .5,
cholesky_NG_c = .5,
cholesky_NG_tol = 0,
cholesky_SSVS_c0 = 0.001,
cholesky_SSVS_c1 = 1,
cholesky_SSVS_p = 0.5,
cholesky_HMP_lambda3 = c(0.01,0.01),
cholesky_normal_sds = 10,
expert_sv_offset = 0,
quiet = FALSE,
...){
if(is.null(data) & !is.numeric(M)){
stop("\nEither provide 'data', the data for the VAR to be estimated, or 'M', the dimensionality of the data (number of time series)!\n")
}
if(M<2 | M%%1!=0){
stop("\nArgument 'M' must be an integer greater or equal to 2.\n")
}
M <- as.integer(M)
if(!is.null(data)){
if(ncol(data) != M){
warning(paste0("\nArgument 'M' does not coincide with 'ncol(data)'. Setting M=", ncol(data),"!\n"))
M <- ncol(data)
}
}
optionals <- list(...)
if(length(optionals)>0){
warning(paste0("\nYou provided an additional argument. Additional argument:\n", if(is.null(names(optionals))) NULL else paste0(names(optionals),"="), optionals ))
}
# error checks 'type'
if(length(type)<=2L & is.character(type)){
if(length(type)==2L) type <- type[1]
if(!(type %in% c("factor", "cholesky"))){
stop("type must be either 'factor' or 'cholesky'.")
}
}else stop("type must be either 'factor' or 'cholesky'.")
# placeholder for cpp (cpp function expects a list with all the following elements)
# (e.g. even if type is specified as cholesky, cpp function requires the 'factor_list')
sv_priormu <- sv_priorphi <- sv_priorh0 <- numeric(1L)
sv_priorsigma2 <- matrix(as.numeric(NA),1,1)
sv_heteroscedastic <- logical(1L)
cholesky_list <- list(
#cholesky_heteroscedastic = logical(1L),
cholesky_priorhomoscedastic = matrix(as.numeric(NA),1,1),
cholesky_U_prior = character(1L),
cholesky_U_tol = numeric(1L),
## GL priors
cholesky_GL_tol = double(1L),
cholesky_a = double(1L),
cholesky_b = double(1L),
cholesky_c = double(1L),
cholesky_GT_vs = double(1L),
cholesky_GT_priorkernel = character(1L),
cholesky_a_vec = double(1L),
cholesky_a_weight = double(1L),
cholesky_norm_consts = double(1L),
cholesky_c_vec = double(1),
cholesky_c_rel_a = logical(1L),
cholesky_GT_hyper = logical(1),
#DL
cholesky_DL_hyper = logical(1L),
cholesky_DL_plus = logical(1L),
#SSVS
cholesky_SSVS_tau0 = double(1L),
cholesky_SSVS_tau1 = double(1L),
cholesky_SSVS_s_a = double(1L),
cholesky_SSVS_s_b = double(1L),
cholesky_SSVS_hyper = logical(1L),
cholesky_SSVS_p = double(1L),
#HM
cholesky_lambda_3 = double(1L),
cholesky_sv_offset = double(1L))
factor_list <- list(factor_factors = integer(1L),
factor_restrinv = matrix(1L,1,1),
factor_ngprior = logical(1L),
factor_columnwise = logical(1L),
factor_shrinkagepriors = list(a = double(1L),
c = double(1L),
d = double(1L)),
factor_facloadtol = numeric(1L),
factor_interweaving = integer(1L),
#factor_heteroskedastic = logical(1L),
factor_priorhomoskedastic = matrix(as.numeric(NA),1,1),
factor_starttau2 = matrix(as.numeric(NA), 1,1)
)
if(type == "factor"){
if(!quiet){
cat("\nSince argument 'type' is specified with 'factor', all arguments starting with 'cholesky_' are being ignored.\n")
}
# error checks for 'factor_factors'
if (!is.numeric(factor_factors) | factor_factors < 0) {
stop("Argument 'factor_factors' (number of latent factor_factors) must be a single number >= 0.")
} else {
factor_list$factor_factors <- as.integer(factor_factors)
}
# error checks for factor_interweaving
if (is.numeric(factor_interweaving) && length(factor_interweaving) == 1) {
factor_list$factor_interweaving <- as.integer(factor_interweaving)
} else {
stop("Argument 'factor_interweaving' must contain a single numeric value.")
}
if (factor_interweaving != 0 & factor_interweaving != 1 & factor_interweaving != 2 & factor_interweaving != 3 & factor_interweaving != 4 & factor_interweaving != 5 & factor_interweaving != 6 & factor_interweaving != 7) {
stop("Argument 'factor_interweaving' must be one of: 0, 1, 2, 3, 4.")
}
# error checks 'factor_restrict'
if(length(factor_restrict)<=2L & is.character(factor_restrict)){
if(length(factor_restrict)==2L) factor_restrict <- factor_restrict[1]
if(!(factor_restrict %in% c("none", "upper"))){
stop("factor_restrict must be either 'none' or 'upper'.")
}
}else stop("factor_restrict must be either 'none' or 'upper'.")
restr <- matrix(FALSE, nrow = M, ncol = factor_factors)
if (factor_restrict == "upper") restr[upper.tri(restr)] <- TRUE
if (factor_interweaving %in% c(1, 2) && any(diag(restr) == TRUE)) {
stop("Setting 'factor_interweaving' to either 1 or 2 and restricting the diagonal elements of the factor loading matrix are not allowed at the same time.")
}
# factorstochvol sampler interpretes 0 as restricted and 1 as unrestricted
factor_list$factor_restrinv <- matrix(as.integer(!restr), nrow = nrow(restr), ncol = ncol(restr))
# error checks for 'factor_priorfacloadtype'
if(length(factor_priorfacloadtype)<=3L & is.character(factor_priorfacloadtype)){
if(length(factor_priorfacloadtype)>1L) factor_priorfacloadtype <- factor_priorfacloadtype[1]
if(!(factor_priorfacloadtype %in% c("rowwiseng", "colwiseng", "normal"))){
stop("factor_priorfacloadtype must be either 'rowwiseng' or 'colwiseng' or 'normal'.")
}
}else stop("factor_priorfacloadtype must be either 'rowwiseng' or 'colwiseng' or 'normal'.")
if (factor_priorfacloadtype == "normal") {
#factor_pfl <- 1L
factor_list$factor_ngprior <- FALSE
} else if (factor_priorfacloadtype == "rowwiseng") {
factor_list$factor_ngprior <- TRUE
factor_list$factor_columnwise <- FALSE
} else if (factor_priorfacloadtype == "colwiseng") {
factor_list$factor_ngprior <- TRUE
factor_list$factor_columnwise <- TRUE
}
# error checks for 'factor_priorng'
if (!is.numeric(factor_priorng) | length(factor_priorng) != 2 | any(factor_priorng <= 0)) {
stop("Argument 'factor_priorng' (prior hyperhyperparameters for Normal-Gamma prior) must be numeric and of length 2.")
}
cShrink <- factor_priorng[1]
dShrink <- factor_priorng[2]
# error checks for 'factor_priorfacload'
if(!is.numeric(factor_priorfacload) | any(factor_priorfacload <= 0)) {
stop("Argument 'priorfacload' must be numeric and positive.")
}
if(is.matrix(factor_priorfacload)) {
if(nrow(factor_priorfacload) != M || ncol(factor_priorfacload) != factor_factors) {
stop("If argument 'priorfacload' is a matrix, it must be of appropriate dimensions.")
}
if (factor_priorfacloadtype == "normal") {
factor_starttau2 <- factor_priorfacload^2
aShrink <- as.numeric(NA)
cShrink <- as.numeric(NA)
dShrink <- as.numeric(NA)
} else if (factor_priorfacloadtype == "rowwiseng") {
factor_starttau2 <- matrix(1, nrow = M, ncol = factor_factors)
aShrink <- factor_priorfacload[,1]
warning("Only first column of 'priorfacload' is used.'")
cShrink <- rep(cShrink, M)
dShrink <- rep(dShrink, M)
} else if (factor_priorfacloadtype == "colwiseng") {
factor_starttau2 <- matrix(1, nrow = M, ncol = factor_factors)
aShrink <- factor_priorfacload[1,]
warning("Only first row of 'priorfacload' is used.'")
cShrink <- rep(cShrink, factor_factors)
dShrink <- rep(dShrink, factor_factors)
} else if (factor_priorfacloadtype == "dl") {
stop("'dl'prior for factorloading is not supported by bayesianVARs!")
# factor_pfl <- 4L
# factor_starttau2 <- matrix(1, nrow = M, ncol = factor_factors)
# aShrink <- factor_priorfacload[1,1]
# warning("Only first element of 'priorfacload' is used.'")
# cShrink <- NA
# dShrink <- NA
}
} else {
if (length(factor_priorfacload) != 1) {
stop("If argument 'priorfacload' isn't a matrix, it must be a single number.")
}
if (factor_priorfacloadtype == "normal") {
factor_starttau2 <- matrix(factor_priorfacload^2, nrow = M, ncol = factor_factors)
aShrink <- as.numeric(NA)
cShrink <- as.numeric(NA)
dShrink <- as.numeric(NA)
} else if (factor_priorfacloadtype == "rowwiseng") {
factor_starttau2 <- matrix(1, nrow = M, ncol = factor_factors)
aShrink <- rep(factor_priorfacload, M)
cShrink <- rep(cShrink, M)
dShrink <- rep(dShrink, M)
} else if (factor_priorfacloadtype == "colwiseng") {
factor_starttau2 <- matrix(1, nrow = M, ncol = factor_factors)
aShrink <- rep(factor_priorfacload, factor_factors)
cShrink <- rep(cShrink, factor_factors)
dShrink <- rep(dShrink, factor_factors)
} else if (factor_priorfacloadtype == "dl") {
stop("'dl' prior for factorloading is not supported by bayesianVARs!")
# factor_pfl <- 4L
# factor_starttau2 <- matrix(1, nrow = M, ncol = factor_factors)
# aShrink <- factor_priorfacload
# cShrink <- NA
# dShrink <- NA
}
}
factor_list$factor_shrinkagepriors <- list(a = aShrink,
c = cShrink,
d = dShrink)
factor_list$factor_starttau2 <- factor_starttau2
# error checks for 'factor_facloadtol'
if(factor_facloadtol < 0){
stop("Argument 'factor_facloadtol' (tolerance for the factor loadings) must be >=0.")
}
factor_list$factor_facloadtol <- factor_facloadtol
# error checks for 'factor_priormu'
if (!is.numeric(factor_priormu) | length(factor_priormu) != 2) {
stop("Argument 'factor_priormu' (mean and sd for the Gaussian prior for mu) must be numeric and of length 2.")
}
if(any(factor_heteroskedastic==TRUE)){
sv_priormu <- factor_priormu
}
# error checks for 'factor_priorphiidi'
if (!is.numeric(factor_priorphiidi) | length(factor_priorphiidi) != 2) {
stop("Argument 'factor_priorphiidi' (shape1 and shape2 parameters for the Beta prior for (phi+1)/2) must be numeric and of length 2.")
}
# error checks for 'factor_priorphifac'
if (!is.numeric(factor_priorphifac) | length(factor_priorphifac) != 2) {
stop("Argument 'factor_priorphifac' (shape1 and shape2 parameters for the Beta prior for (phi+1)/2) must be numeric and of length 2.")
}
if(any(factor_heteroskedastic==TRUE)){
sv_priorphi <- c(factor_priorphiidi, factor_priorphifac)
}
# error checks for 'factor_priorsigmaidi'
if (!is.numeric(factor_priorsigmaidi) | any(factor_priorsigmaidi <= 0)) {
stop("Argument 'factor_priorsigmaidi' (scaling of the chi-squared(df = 1) prior for sigma^2) must be numeric and > 0.")
}
if(!(length(factor_priorsigmaidi)==1 | length(factor_priorsigmaidi) == M)){
stop("Argument 'factor_priorsigmaidi' must be either of length 1 or M.")
}
factor_priorsigmaidi <- rep_len(factor_priorsigmaidi, M)
# error checks for 'factor_priorsigmafac'
if (!is.numeric(factor_priorsigmafac) | any(factor_priorsigmafac <= 0)) {
stop("Argument 'factor_priorsigmafac' (scaling of the chi-squared(df = 1) prior for sigma^2) must be numeric and > 0.")
}
if (length(factor_priorsigmafac) == 1) {
factor_priorsigmafac <- rep(factor_priorsigmafac, factor_factors)
} else if (length(factor_priorsigmafac) == factor_factors) {
factor_priorsigmafac <- factor_priorsigmafac
} else {
stop("Argument 'factor_priorsigmafac' (scaling of the chi-squared(df = 1) prior for sigma^2) must of length 1 or factor_factors")
}
factor_priorsigma <- c(factor_priorsigmaidi, factor_priorsigmafac)
# factorstochvol specifies chi-squared prior, stochvol however is parametrized in gamma:
if(any(factor_heteroskedastic==TRUE)){
sv_priorsigma2 <- cbind(0.5,0.5/factor_priorsigma)
}
# error checks for factor_priorh0idi
factor_priorh0idi[remember <- factor_priorh0idi == "stationary"] <- -1
factor_priorh0idi[!remember] <- as.numeric(factor_priorh0idi[!remember])^2
factor_priorh0idi <- as.numeric(factor_priorh0idi)
if (any(factor_priorh0idi[!remember] < 0)) stop("Argument 'priorh0idi' must not contain negative values.")
if(!(length(factor_priorh0idi) == 1 | length(factor_priorh0idi) == M)){
stop("Argument 'factor_priorh0idi' must be either of length 1 or M.")
}
factor_priorh0idi <- rep_len(factor_priorh0idi,M)
# error checks for factor_priorh0fac
if (length(factor_priorh0fac) == 1) factor_priorh0fac <- rep(factor_priorh0fac, factor_factors)
if (length(factor_priorh0fac) != factor_factors) stop("Argument 'factor_priorh0fac' must be of length 1 or factor_factors.")
factor_priorh0fac[remember <- factor_priorh0fac == "stationary"] <- -1
factor_priorh0fac[!remember] <- as.numeric(factor_priorh0fac[!remember])^2
factor_priorh0fac <- as.numeric(factor_priorh0fac)
if (any(factor_priorh0fac[!remember] < 0)) stop("Argument 'factor_priorh0fac' must not contain negative values.")
sv_priorh0 <- c(factor_priorh0idi, factor_priorh0fac)
# Some error checking for factor_heteroskedastic
if (length(factor_heteroskedastic) == 1) factor_heteroskedastic <- rep(factor_heteroskedastic, M + factor_factors)
if (length(factor_heteroskedastic) == 2) factor_heteroskedastic <- c(rep(factor_heteroskedastic[1], M), rep(factor_heteroskedastic[2], factor_factors))
if (length(factor_heteroskedastic) != M + factor_factors) stop("Argument 'factor_heteroskedastic' must be of length 1, 2, or (ncol(y) + factor_factors).")
if (!is.logical(factor_heteroskedastic)) stop("Argument 'factor_heteroskedastic' must be a vector containing only logical values.")
if (is.null(factor_heteroskedastic)) factor_heteroskedastic <- rep(TRUE, M + factor_factors)
if (!all(factor_heteroskedastic[M+seq_len(factor_factors)])) {
if (factor_interweaving == 2L || factor_interweaving == 4L) {
if(!quiet){
cat("\nCannot do deep factor_interweaving if (some) factor_factors are homoskedastic. Setting 'factor_interweaving' to 3.\n")
}
factor_list$factor_interweaving <- 3L
}
}
if (!all(factor_heteroskedastic)) {
if (any(is.na(factor_priorhomoskedastic))) {
factor_priorhomoskedastic <- matrix(c(1.1, 0.055), byrow = TRUE, nrow = M, ncol = 2)
if(!quiet){
cat(paste0("\nArgument 'factor_priorhomoskedastic' must be a matrix with dimension c(M, 2) if some of the
elements of 'factor_heteroskedastic' are FALSE. Setting factor_priorhomoskedastic to a matrix with
all rows equal to c(", factor_priorhomoskedastic[1], ", ", factor_priorhomoskedastic[2], ").\n"))
}
}
if (!is.matrix(factor_priorhomoskedastic) || nrow(factor_priorhomoskedastic) != M ||
ncol(factor_priorhomoskedastic) != 2 || any(factor_priorhomoskedastic <= 0)) {
stop("Argument 'factor_priorhomoskedastic' must be a matrix with positive entries and dimension c(M, 2).")
}
}
sv_heteroscedastic <- factor_heteroskedastic
factor_list$factor_priorhomoskedastic <- as.matrix(factor_priorhomoskedastic)
}else if(type == "cholesky"){
if(!quiet){
cat("\nSince argument 'type' is specified with 'cholesky', all arguments starting with 'factor_' are being ignored.\n")
}
n_U <- (M^2-M)/2 # number of free off diagonal elements in U
# error checks for cholesky_heteroscedastic
if(!is.logical(cholesky_heteroscedastic) | length(cholesky_heteroscedastic) > 1L){
stop("Argument 'cholesky_heteroscedastic' must be a single logical.")
}
sv_heteroscedastic <- rep_len(cholesky_heteroscedastic, M)
# error checks for cholesky_priormu
if(!is.numeric(cholesky_priormu) | length(cholesky_priormu) != 2){
stop("Argument 'choleksy_priormu' must be a numeric vector of length 2, where the
second element must be posistive.")
}
if(cholesky_priormu[2]<0){
stop("Argument 'choleksy_priormu' must be a numeric vector of length 2, where the
second element must be posistive.")
}
if(cholesky_heteroscedastic){
sv_priormu <- cholesky_priormu
}