-
Notifications
You must be signed in to change notification settings - Fork 22
/
blavaan.R
1049 lines (951 loc) · 41.8 KB
/
blavaan.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
blavaan <- function(..., # default lavaan arguments
# bayes-specific stuff
cp = "srs",
dp = NULL,
n.chains = 3,
burnin ,
sample ,
adapt ,
mcmcfile = FALSE,
mcmcextra = list(),
inits = "prior",
convergence = "manual",
target = "stan",
save.lvs = FALSE,
wiggle = NULL,
wiggle.sd = 0.1,
prisamp = FALSE,
jags.ic = FALSE,
seed = NULL,
bcontrol = list()
)
{
## start timer
start.time0 <- proc.time()[3]
# store original call
mc <- match.call()
# catch dot dot dot
dotdotdot <- list(...); dotNames <- names(dotdotdot)
# default priors
if(length(dp) == 0) dp <- dpriors(target = target)
# burnin/sample/adapt if not supplied (should only occur for direct
# blavaan call
sampargs <- c("burnin", "sample", "adapt")
suppargs <- which(!(sampargs %in% names(mc)))
if(length(suppargs) > 0){
if(target == "jags"){
defiters <- c(4000L, 10000L, 1000L)
} else {
defiters <- c(500L, 1000L, 1000L)
}
for(i in 1:length(suppargs)){
assign(sampargs[suppargs[i]], defiters[suppargs[i]])
}
}
# multilevel functionality not available
if("cluster" %in% dotNames) stop("blavaan ERROR: two-level models are not yet available.")
# prior predictives only for stan
if(prisamp) {
if(target != 'stan') stop("blavaan ERROR: prior predictives currently only work for target='stan'.")
if(!('test' %in% dotNames)) {
dotdotdot$test <- 'none'
dotNames <- c(dotNames, "test")
}
}
# wiggle sd
if(any(wiggle.sd <= 0L)) stop("blavaan ERROR: wiggle.sd must be > 0.")
if(length(wiggle) > 0 & target == 'stancond') stop(paste0("blavaan ERROR: wiggle is currently not available for target ", target))
if(length(wiggle.sd) > 1){
if(target != 'stan') stop("blavaan ERROR: parameter-specific wiggle.sd is only available for target='stan'")
if(length(wiggle.sd) != length(wiggle)) stop("blavaan ERROR: length of wiggle.sd must match length of wiggle")
}
# no current functionality to generate initial values from approximately-equal prior
if(length(wiggle) > 0 & target %in% c('stanclassic', 'jags') & inherits(inits, 'character')) inits <- "simple"
# mcmcextra args
if(length(mcmcextra) > 0){
goodnm <- names(mcmcextra) %in% c('data', 'monitor', 'syntax', 'llnsamp')
if(!all(goodnm)){
stop(paste0("blavaan ERROR: invalid list names in mcmcextra:\n ", paste(names(mcmcextra)[!goodnm], collapse=" ")))
}
}
# ensure rstan/runjags are here. if target is not installed but
# the other is, then use the other instead.
if(grepl("stan", target)){
if(convergence == "auto") stop("blavaan ERROR: auto convergence is unavailable for Stan.")
if(target == "stan" & length(mcmcextra) > 0) {
if("syntax" %in% names(mcmcextra)) stop("blavaan ERROR: mcmcextra$syntax is not available for target='stan'.")
}
} else if(target == "jags"){
if(!pkgcheck("runjags")){
## go to rstan if they have it
if(pkgcheck("rstan")){
cat("blavaan NOTE: runjags not installed; using rstan instead.\n")
target <- "stan"
pkgload("rstan")
} else {
stop("blavaan ERROR: runjags package is not installed.")
}
} else {
pkgload("runjags")
}
}
# if seed supplied, check that there is one per chain
seedlen <- length(seed)
if(seedlen > 0 & target == "jags" & seedlen != n.chains){
stop("blavaan ERROR: for JAGS, number of seeds must equal n.chains.")
}
# capture data augmentation/full information options
blavmis <- "da"
if("missing" %in% dotNames) {
if(dotdotdot$missing %in% c("da", "fi")) {
blavmis <- dotdotdot$missing
misloc <- which(dotNames == "missing")
dotdotdot <- dotdotdot[-misloc]; dotNames <- dotNames[-misloc]
}
}
# covariance priors are now all srs or fa
cplocs <- match(c("ov.cp", "lv.cp"), dotNames, nomatch = 0)
if(any(cplocs > 0)){
cat("blavaan NOTE: Arguments ov.cp and lv.cp are deprecated. Use cp instead. \n")
if(any(dotdotdot[cplocs] == "fa")){
cp <- "fa"
cat("Using 'fa' approach for all covariances.\n")
} else {
cat("\n")
}
if(!all(dotdotdot[cplocs] %in% c("srs", "fa"))){
stop("blavaan ERROR: unknown argument to cp.")
}
dotdotdot <- dotdotdot[-cplocs]; dotNames <- dotNames[-cplocs]
}
## cannot use lavaan inits with fa priors; FIXME?
if(cp == "fa" & inherits(inits, 'character')){
if(inits[1] %in% c("simple", "default")) inits <- "jags"
}
if(cp == "fa" & grepl("stan", target)){
cat("blavaan NOTE: fa priors are not available with stan. srs priors will be used. \n")
}
# 'jag' arguments are now mcmcfile, mcmcextra, bcontrol
jagargs <- c("jagfile", "jagextra")
barg <- "jagcontrol"
jaglocs <- match(jagargs, dotNames, nomatch = 0)
blocs <- match(barg, dotNames, nomatch = 0)
if(any(jaglocs > 0)){
cat(paste0("blavaan NOTE: the following argument(s) are deprecated: ",
paste(jagargs[jaglocs > 0], collapse=" "),
".\n the argument(s) now start with 'mcmc' instead of 'jag'. \n"))
newargs <- gsub("jag", "mcmc", jagargs[jaglocs > 0])
for(i in 1:length(newargs)){
assign(newargs[i], dotdotdot[[jaglocs[jaglocs > 0][i]]])
}
dotdotdot <- dotdotdot[-jaglocs]; dotNames <- dotNames[-jaglocs]
}
if(any(blocs > 0)){
cat(paste0("blavaan NOTE: the following argument is deprecated: ",
paste(barg[blocs > 0], collapse=" "),
".\n the argument now starts with 'b' instead of 'jag'. \n"))
newargs <- gsub("jag", "b", barg[blocs > 0])
for(i in 1:length(newargs)){
assign(newargs[i], dotdotdot[[blocs[blocs > 0][i]]])
}
dotdotdot <- dotdotdot[-blocs]; dotNames <- dotNames[-blocs]
}
# which arguments do we override?
lavArgsOverride <- c("meanstructure", "missing", "estimator", "conditional.x")
# always warn?
warn.idx <- which(lavArgsOverride %in% dotNames)
if(length(warn.idx) > 0L) {
warning("blavaan WARNING: the following arguments have no effect:\n",
" ",
paste(lavArgsOverride[warn.idx], collapse = " "), call. = FALSE)
}
# if do.fit supplied, save it for jags stuff
jag.do.fit <- TRUE
if("do.fit" %in% dotNames){
jag.do.fit <- dotdotdot$do.fit
if(!jag.do.fit){
burnin <- 0
sample <- 0
}
}
if("warn" %in% dotNames){
origwarn <- dotdotdot$warn
} else {
origwarn <- TRUE
}
if("test" %in% dotNames){
origtest <- dotdotdot$test
} else {
origtest <- "standard"
}
dotdotdot$do.fit <- FALSE
dotdotdot$se <- "none"; dotdotdot$test <- "none"
# run for 1 iteration to obtain info about equality constraints, for npar
dotdotdot$control <- list(iter.max = 1); dotdotdot$warn <- TRUE
dotdotdot$optim.force.converged <- TRUE
dotdotdot$meanstructure <- TRUE
dotdotdot$missing <- "direct" # direct/ml creates error? (bug in lavaan?)
if("ordered" %in% dotNames |
any(apply(dotdotdot$data, 2, function(x) inherits(x, "ordered")))){
dotdotdot$missing <- "pairwise" # needed to get missing patterns
if("parameterization" %in% names(dotdotdot)){
if(dotdotdot$parameterization == "delta"){
warning("blavaan WARNING: the parameterization argument has no effect; theta parameterization will be used.", call. = FALSE)
}
}
}
dotdotdot$parameterization <- "theta"
dotdotdot$estimator <- "default"
dotdotdot$conditional.x <- FALSE
# jags args
if("debug" %in% dotNames) {
if(dotdotdot$debug) {
## short burnin/sample
burnin <- 100
sample <- 100
}
}
mfj <- list(burnin = burnin, sample = sample, adapt = adapt)
if(target == "stancond") cat("\nblavaan NOTE: target='stancond' is experimental and may not be fully functional\n")
if(convergence == "auto"){
names(mfj) <- c("startburnin", "startsample", "adapt")
}
if(grepl("stan", target)){
names(mfj) <- c("warmup", "iter", "adapt")
## stan iter argument includes warmup:
mfj$iter <- mfj$warmup + mfj$iter
mfj <- mfj[-which(names(mfj) == "adapt")]
}
if(target == "jags"){
mfj <- c(mfj, list(n.chains = n.chains))
} else {
mfj <- c(mfj, list(chains = n.chains))
}
if(convergence == "auto"){
if(!("startsample" %in% names(mfj))){
## bump down default
mfj$startsample <- 4000
} else {
if(mfj$startsample < 4000){
cat("blavaan NOTE: starting sample was increased to 4000 for auto-convergence\n")
mfj$startsample <- 4000 # needed for runjags
}
}
sample <- mfj$startsample
if(!("startburnin" %in% names(mfj))){
mfj$startburnin <- 4000
burnin <- 4000
} else {
burnin <- mfj$startburnin
}
}
# which argument do we remove/ignore?
lavArgsRemove <- c("likelihood", "information", "se", "bootstrap",
"wls.v", "nacov", "zero.add", "zero.keep.margins",
"zero.cell.warn")
dotdotdot[lavArgsRemove] <- NULL
warn.idx <- which(lavArgsRemove %in% dotNames)
if(length(warn.idx) > 0L) {
warning("blavaan WARNING: the following arguments are ignored:\n",
" ",
paste(lavArgsRemove[warn.idx], collapse = " "), call. = FALSE)
}
# call lavaan
mcdebug <- FALSE
if("debug" %in% dotNames){
## only debug mcmc stuff
mcdebug <- dotdotdot$debug
dotdotdot <- dotdotdot[-which(dotNames == "debug")]
}
# for warnings related to setting up model/data:
LAV <- do.call("lavaan", dotdotdot)
dotdotdot$do.fit <- TRUE; dotdotdot$warn <- FALSE
# for initial values/parameter setup:
LAV <- do.call("lavaan", dotdotdot)
if(LAV@Data@data.type == "moment") {
stop("blavaan ERROR: full data are required. consider using kd() from package semTools.")
}
# save.lvs in a model with no lvs
if(save.lvs){
clv <- lavInspect(LAV, 'cov.lv')
if(is.list(clv)) clv <- clv[[1]]
if(nrow(clv) == 0) warning("blavaan WARNING: save.lvs=TRUE, but there are no lvs in the model.", call. = FALSE)
}
# turn warnings back on by default
LAV@Options$warn <- origwarn
# put original do.fit + test back
LAV@Options$do.fit <- jag.do.fit
dotdotdot$test <- origtest
# check for conflicting mv names
namecheck(LAV@Data@ov.names[[1]])
# ordinal only for stan
ordmod <- lavInspect(LAV, 'categorical')
if(ordmod) {
if(target != "stan") stop("blavaan ERROR: ordinal variables only work for target='stan'.")
}
ineq <- which(LAV@ParTable$op %in% c("<",">"))
if(length(ineq) > 0) {
LAV@ParTable <- lapply(LAV@ParTable, function(x) x[-ineq])
if(inherits(mcmcfile, "logical")) mcmcfile <- TRUE
warning("blavaan WARNING: blavaan does not currently handle inequality constraints.\n try modifying the exported MCMC syntax.", call. = FALSE)
}
eqs <- which(LAV@ParTable$op == "==")
if(length(eqs) > 0) {
lhsvars <- rep(NA, length(eqs))
for(i in 1:length(eqs)){
lhsvars[i] <- length(all.vars(parse(file="", text=LAV@ParTable$lhs[eqs[i]])))
}
if(any(lhsvars > 1)) {
stop("blavaan ERROR: blavaan does not handle equality constraints with more than 1 variable on the lhs.\n try modifying the constraints.")
}
}
prispec <- "prior" %in% names(LAV@ParTable)
# cannot currently use wishart prior with std.lv=TRUE
if(LAV@Options$auto.cov.lv.x & LAV@Options$std.lv){
#warning("blavaan WARNING: cannot use Wishart prior with std.lv=TRUE. Reverting to 'srs' priors.")
LAV@Options$auto.cov.lv.x <- FALSE
}
# Check whether there are user-specified priors or equality
# constraints on lv.x or ov.x. If so, set auto.cov.lv.x = FALSE.
lv.x <- LAV@pta$vnames$lv.x[[1]]
## catch some regressions without fixed x:
ov.noy <- LAV@pta$vnames$ov.nox[[1]]
ov.noy <- ov.noy[!(ov.noy %in% LAV@pta$vnames$ov.y)]
ndpriors <- rep(FALSE, length(LAV@ParTable$lhs))
if(prispec) ndpriors <- LAV@ParTable$prior != ""
cov.pars <- (LAV@ParTable$lhs %in% c(lv.x, ov.noy)) & LAV@ParTable$op == "~~"
con.cov <- any((cov.pars & (LAV@ParTable$free == 0 | ndpriors)) |
((LAV@ParTable$lhs %in% LAV@ParTable$plabel[cov.pars] |
LAV@ParTable$rhs %in% LAV@ParTable$plabel[cov.pars]) &
LAV@ParTable$op == "=="))
if(con.cov) LAV@Options$auto.cov.lv.x <- FALSE
# if std.lv, truncate the prior of each lv's first loading
loadpt <- LAV@ParTable$op == "=~"
lvs <- unique(LAV@ParTable$lhs[loadpt])
if(LAV@Options$std.lv){
if(cp == "fa") stop("blavaan ERROR: 'fa' prior strategy cannot be used with std.lv=TRUE.")
if(!prispec){
LAV@ParTable$prior <- rep("", length(LAV@ParTable$id))
}
fload <- NULL
if(length(lvs) > 0){
for(i in 1:length(lvs)){
for(k in 1:max(LAV@ParTable$group)){
fload <- c(fload, which(LAV@ParTable$lhs == lvs[i] &
LAV@ParTable$op == "=~" &
LAV@ParTable$group == k)[1])
}
}
## NB truncation doesn't work well in stan. instead
## use generated quantities after the fact.
trunop <- " T(0,)"
if(target == "jags"){
for(i in 1:length(fload)){
if(LAV@ParTable$prior[fload[i]] != ""){
LAV@ParTable$prior[fload[i]] <- paste(LAV@ParTable$prior[fload[i]], trunop, sep="")
}
}
}
}
} else {
## check for lvs fixed to 1
if(any(LAV@ParTable$op == "~~" &
LAV@ParTable$free == 0 &
LAV@ParTable$lhs == LAV@ParTable$rhs &
LAV@ParTable$ustart == 1L &
LAV@ParTable$lhs %in% lvs)){
warning("blavaan WARNING: If you are manually fixing lv variances to 1 for identification, ",
"please use std.lv=TRUE.", call. = FALSE)
}
}
# if mcmcfile is a directory, vs list, vs logical
trans.exists <- FALSE
if(inherits(mcmcfile, "character")){
jagdir <- mcmcfile
mcmcfile <- TRUE
} else if(inherits(mcmcfile, "list")){
trans.exists <- TRUE
## read syntax file
jagsyn <- readLines(mcmcfile$syntax)
## load jagtrans object
load(mcmcfile$jagtrans)
## add new syntax
jagtrans$model <- paste(jagsyn, collapse="\n")
## make sure we don't rewrite the file:
mcmcfile <- FALSE
## we have no idea what they did, so wipe out the priors
jagtrans$coefvec$prior <- ""
jagdir <- "lavExport"
} else {
jagdir <- "lavExport"
}
# if inits is list
initsin <- inits
if(inherits(inits, "list")) initsin <- "jags"
# extract slots from dummy lavaan object
lavpartable <- LAV@ParTable
if(!("prior" %in% names(lavpartable))) lavpartable$prior <- rep("", length(lavpartable$lhs))
lavmodel <- LAV@Model
lavdata <- LAV@Data
lavoptions <- LAV@Options
lavsamplestats <- LAV@SampleStats
lavcache <- LAV@Cache
timing <- LAV@timing
# change some 'default' @Options and add some
lavoptions$estimator <- "Bayes"
lavoptions$se <- "standard"
lavoptions$test <- "standard"
if(ordmod) {
cat("blavaan NOTE: ordinal models are new, please report bugs!\nhttps://github.com/ecmerkle/blavaan/issues\n\n")
}
if("test" %in% dotNames) {
if(dotdotdot$test == "none") lavoptions$test <- "none"
} else {
# if missing data, posterior predictives are way slow
if(any(is.na(unlist(LAV@Data@X))) & target != "stan") {
cat("blavaan NOTE: Posterior predictives with missing data are currently very slow.\n\tConsider setting test=\"none\".\n\n")
}
}
if(!jag.do.fit){
lavoptions$test <- "none"
lavoptions$se <- "none"
}
lavoptions$missing <- "ml"
lavoptions$cp <- cp
lavoptions$dp <- dp
lavoptions$prisamp <- prisamp
lavoptions$target <- target
if("llnsamp" %in% names(mcmcextra$data)){
if(length(mcmcextra$data$llnsamp) > 1 ||
(!inherits(mcmcextra$data$llnsamp, "numeric") &&
!(inherits(mcmcextra$data$llnsamp, "integer")))){
stop("blavaan ERROR: llnsamp must be a single integer.\n\n")
}
lavoptions$llnsamp <- mcmcextra$data$llnsamp
}
verbose <- lavoptions$verbose
# redo estimation + vcov + test
# 6. estimate free parameters
start.time <- proc.time()[3]
x <- NULL
if(lavmodel@nx.free > 0L) {
if(!trans.exists){
## convert partable to mcmc syntax, then run
if(target == "jags"){
jagtrans <- try(lav2mcmc(model = lavpartable, lavdata = lavdata,
cp = cp, lv.x.wish = lavoptions$auto.cov.lv.x,
dp = dp, n.chains = n.chains,
mcmcextra = mcmcextra, inits = initsin,
blavmis = blavmis, wiggle = wiggle,
wiggle.sd = wiggle.sd, target = "jags"),
silent = TRUE)
} else if(target == "stanclassic"){
jagtrans <- try(lav2stan(model = LAV,
lavdata = lavdata,
dp = dp, n.chains = n.chains,
mcmcextra = mcmcextra,
inits = initsin, wiggle = wiggle,
wiggle.sd = wiggle.sd, debug = mcdebug),
silent = TRUE)
} else if(target == "stancond"){
jagtrans <- try(lav2stancond(model = LAV,
lavdata = lavdata,
dp = dp, n.chains = n.chains,
mcmcextra = mcmcextra,
inits = initsin,
debug = mcdebug),
silent = TRUE)
} else {
l2s <- try(lav2stanmarg(lavobject = LAV, dp = dp,
n.chains = n.chains, mcmcextra = mcmcextra,
inits = initsin, wiggle = wiggle,
wiggle.sd = wiggle.sd, prisamp = prisamp),
silent = TRUE)
if(!inherits(l2s, "try-error")){
lavpartable$prior[as.numeric(rownames(l2s$lavpartable))] <- l2s$lavpartable$prior
ldargs <- c(l2s$dat, list(lavpartable = l2s$lavpartable, dumlv = l2s$dumlv,
save_lvs = save.lvs, do_test = !(lavoptions$test == "none") ))
## add priors to lavpartable, including wiggle
if(length(wiggle) > 0){
wigrows <- which(l2s$wigpris != "")
lavpartable$prior[as.numeric(rownames(l2s$lavpartable))[wigrows]] <- l2s$wigpris[wigrows]
}
jagtrans <- try(do.call("stanmarg_data", ldargs), silent = TRUE)
if(inherits(jagtrans, "try-error")) stop(jagtrans)
## add lkj for unrestricted psi
if(jagtrans$fullpsi == 1L){
psirows <- which(l2s$lavpartable$mat == "lvrho")
lavpartable$prior[as.numeric(rownames(l2s$lavpartable))[psirows]] <- paste0("lkj_corr(", jagtrans$psi_r_alpha[1], ")")
}
jagtrans <- list(data = jagtrans,
monitors = c("ly_sign",
#"lx_sign",
"bet_sign", "g_sign",
"Theta_cov", "Theta_var",
#"Theta_x_cov", "Theta_x_var",
"Psi_cov", "Psi_var",
#"Ph_cov", "Ph_var",
"Nu_free", "Alpha_free", "Tau_free",
"log_lik", "log_lik_sat", "ppp"))
if("init" %in% names(l2s)){
jagtrans <- c(jagtrans, list(inits = l2s$init))
}
if(ordmod && save.lvs){
jagtrans$monitors <- c(jagtrans$monitors, "YXostar")
}
} else {
jagtrans <- l2s
}
}
}
if(!inherits(jagtrans, "try-error")){
## add extras
if(length(mcmcextra) > 0){
if("monitor" %in% names(mcmcextra)){
jagtrans$monitors <- c(jagtrans$monitors, mcmcextra$monitor)
}
if("data" %in% names(mcmcextra)){
tmpdat <- c(jagtrans$data, mcmcextra$data)
## if a piece of data appears in both jagtrans and mcmcextra, prefer
## the one from mcmcextra:
jagtrans$data <- tmpdat[!duplicated(names(tmpdat), fromLast = TRUE)]
}
}
sampparms <- jagtrans$monitors
if(save.lvs & target != "stan") sampparms <- c(sampparms, "eta")
if(initsin == "jags"){
jagtrans$inits <- vector("list", n.chains)
}
if(inherits(inits, "list")) jagtrans$inits <- inits
## add seed to inits; for stan, just add it to
## bcontrol
if(seedlen > 0 & target == "jags"){
sdinit <- lapply(seed, function(x) list(.RNG.seed = x,
.RNG.name = "base::Super-Duper"))
for(i in 1:n.chains){
jagtrans$inits[[i]] <- c(jagtrans$inits[[i]], sdinit[[i]])
}
} else if(seedlen > 0 & grepl("stan", target)){
if(!("seed" %in% names(bcontrol))){
bcontrol <- c(bcontrol, list(seed = seed))
}
}
if(mcmcfile){
dir.create(path=jagdir, showWarnings=FALSE)
fext <- ifelse(target=="jags", "jag", "stan")
fnm <- paste0(jagdir, "/sem.", fext)
if(target=="stan"){
cat(stanmodels$stanmarg@model_code, file = fnm)
} else {
cat(jagtrans$model, file = fnm)
}
if(target=="jags"){
save(jagtrans, file = paste(jagdir, "/semjags.rda",
sep=""))
} else {
stantrans <- jagtrans
save(stantrans, file = paste(jagdir, "/semstan.rda",
sep=""))
}
}
if(target == "jags"){
rjarg <- with(jagtrans, list(model = paste(model),
monitor = sampparms,
data = data, inits = inits))
} else if(target %in% c("stanclassic", "stancond")){
rjarg <- with(jagtrans, list(model_code = model,
pars = sampparms,
data = data,
init = inits))
} else {
rjarg <- with(jagtrans, list(object = stanmodels$stanmarg,
data = data,
pars = sampparms,
init = inits))
}
## user-supplied jags params
rjarg <- c(rjarg, mfj, bcontrol)
if(target == "jags"){
## obtain posterior modes
## turned off because runjags needs updated
if(suppressMessages(requireNamespace("modeest", quietly = TRUE))) runjags::runjags.options(mode.continuous = FALSE)
runjags::runjags.options(force.summary = TRUE)
}
if(jag.do.fit){
if(target == "jags"){
rjcall <- "run.jags"
} else if(target %in% c("stanclassic", "stancond")){
cat("Compiling stan model...")
rjcall <- "stan"
} else {
rjcall <- "sampling"
}
if(convergence == "auto"){
rjcall <- "autorun.jags"
if("raftery.options" %in% names(rjarg)){
## autorun defaults
if(!("r" %in% names(rjarg$raftery.options))){
rjarg$raftery.options$r <- .01
}
if(!("converge.eps" %in% names(rjarg$raftery.options))){
rjarg$raftery.options$converge.eps <- .01
}
} else {
rjarg$raftery.options <- list(r=.01, converge.eps=.01)
}
}
## the model is run here:
res <- try(do.call(rjcall, rjarg))
} else {
res <- NULL
}
if(inherits(res, "try-error")) {
if(!trans.exists){
dir.create(path=jagdir, showWarnings=FALSE)
fext <- ifelse(target=="jags", "jag", "stan")
cat(jagtrans$model, file = paste(jagdir, "/sem.",
fext, sep=""))
if(target=="jags"){
save(jagtrans, file = paste(jagdir, "/semjags.rda",
sep=""))
} else {
stantrans <- jagtrans
save(stantrans, file = paste(jagdir, "/semstan.rda",
sep=""))
}
}
stop("blavaan ERROR: problem with MCMC estimation. The model syntax and data have been exported.")
}
} else {
print(jagtrans)
stop("blavaan ERROR: problem with translation from lavaan to MCMC syntax.")
}
timing$Estimate <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
if(target == "jags"){
parests <- coeffun(lavpartable, jagtrans$pxpartable, res)
stansumm <- NA
} else if(target %in% c("stanclassic", "stancond")){
parests <- coeffun_stan(lavpartable, jagtrans$pxpartable,
res)
stansumm <- parests$stansumm
} else {
parests <- coeffun_stanmarg(lavpartable, lavInspect(LAV, 'free'), l2s$free2, jagtrans$data, res)
stansumm <- parests$stansumm
}
x <- parests$x
lavpartable <- parests$lavpartable
if(jag.do.fit){
lavmodel <- lav_model_set_parameters(lavmodel, x = x)
if(target == "jags"){
attr(x, "iterations") <- res$sample
sample <- res$sample
burnin <- res$burnin
} else {
wrmup <- ifelse(length(rjarg$warmup) > 0,
rjarg$warmup, floor(rjarg$iter/2))
attr(x, "iterations") <- sample
if(target == "stan"){
## defined variables come from delta method:
lavpartable$est <- lav_model_get_parameters(lavmodel = lavmodel, type = "user", extra = TRUE)
}
## lvs now in R instead of Stan
if(save.lvs & target == "stan"){
stanlvs <- samp_lvs(res, lavmodel, parests$lavpartable, jagtrans$data, lavoptions$categorical)
if(dim(stanlvs)[3L] > 0){
lvsumm <- as.matrix(rstan::monitor(stanlvs, print=FALSE))
cmatch <- match(colnames(stansumm), colnames(lvsumm))
stansumm <- rbind(stansumm, lvsumm[,cmatch])
}
}
# burnin + sample already defined, will be saved in
# @external so summary() can use it:
#burnin <- wrmup
#sample <- sample - wrmup
}
attr(x, "converged") <- TRUE
} else {
x <- numeric(0L)
attr(x, "iterations") <- 0L
attr(x, "converged") <- FALSE
lavpartable$est <- lavpartable$start
stansumm <- NULL
stanlvs <- NULL
}
attr(x, "control") <- bcontrol
## log-likelihoods
tmplo <- lavoptions
tmplo$target <- "jags" ## to ensure computation in R, vs extraction of the
## log-likehoods from Stan
## FIXME: modify so that fx is commensurate with logl from Stan
## for ystar, could take means of truncated normals
attr(x, "fx") <- get_ll(lavmodel = lavmodel, lavpartable = lavpartable,
lavsamplestats = lavsamplestats, lavoptions = tmplo,
lavcache = lavcache, lavdata = lavdata,
lavobject = LAV, standata = rjarg$data)[1]
if(save.lvs & jag.do.fit & !ordmod) {
if(target == "jags"){
fullpmeans <- summary(make_mcmc(res))[[1]][,"Mean"]
} else {
fullpmeans <- stansumm[,"mean"] #rstan::summary(res)$summary[,"mean"]
}
cfx <- get_ll(fullpmeans, lavmodel = lavmodel, lavpartable = lavpartable,
lavsamplestats = lavsamplestats, lavoptions = lavoptions,
lavcache = lavcache, lavdata = lavdata,
lavobject = LAV, conditional = TRUE)[1]
} else {
cfx <- NULL
}
}
## parameter convergence + implied moments:
lavimplied <- NULL
## compute/store some model-implied statistics
lavimplied <- lav_model_implied(lavmodel, delta = (lavmodel@parameterization == "delta"))
if(jag.do.fit & n.chains > 1){
## this also checks convergence of monitors from mcmcextra, which may not be optimal
psrfrows <- which(!is.na(lavpartable$psrf) &
!is.na(lavpartable$free) &
lavpartable$free > 0)
if(any(lavpartable$psrf[psrfrows] > 1.2)) attr(x, "converged") <- FALSE
## warn if psrf is large
if(!attr(x, "converged") && lavoptions$warn) {
warning("blavaan WARNING: at least one parameter has a psrf > 1.2.", call. = FALSE)
}
}
## fx is mean ll, where ll is marginal log-likelihood (integrate out lvs)
if(lavoptions$test != "none") {
cat("Computing posterior predictives...\n")
lavmcmc <- make_mcmc(res)
samplls <- samp_lls(res, lavmodel, lavpartable, lavsamplestats,
lavoptions, lavcache, lavdata, lavmcmc, lavobject = LAV,
standata = rjarg$data)
if(jags.ic) {
sampkls <- samp_kls(res, lavmodel, lavpartable,
lavsamplestats, lavoptions, lavcache,
lavdata, lavmcmc, conditional = FALSE)
} else {
sampkls <- NA
}
if(save.lvs & !ordmod) {
if(target == "stan"){
lavmcmc <- make_mcmc(res, stanlvs) ## add on lvs
}
csamplls <- samp_lls(res, lavmodel, lavpartable,
lavsamplestats, lavoptions, lavcache,
lavdata, lavmcmc, lavobject = LAV,
conditional = TRUE)
if(jags.ic) {
csampkls <- samp_kls(res, lavmodel, lavpartable,
lavsamplestats, lavoptions, lavcache,
lavdata, lavmcmc, lavobject = LAV,
conditional = TRUE)
}
}
} else {
samplls <- NA
sampkls <- NA
csamplls <- NA
csampkls <- NA
}
timing$PostPred <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
## put runjags output in new blavaan slot
lavjags <- res
## 7. VCOV is now simple
lavvcov <- list()
VCOV <- NULL
if(jag.do.fit){
dsd <- parests$sd[names(parests$sd) %in% colnames(parests$vcorr)]
if(length(dsd) > 1) dsd <- diag(dsd)
VCOV <- dsd %*% parests$vcorr %*% dsd
rownames(VCOV) <- colnames(VCOV) <- colnames(parests$vcorr)
#lavjags <- c(lavjags, list(vcov = VCOV))
# store vcov in new @vcov slot
# strip all attributes but 'dim'
tmp.attr <- attributes(VCOV)
VCOV1 <- VCOV
attributes(VCOV1) <- tmp.attr["dim"]
lavvcov <- list(vcov = VCOV1)
}
timing$VCOV <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
## 8. "test statistics": marginal log-likelihood, dic
TEST <- list()
if(lavoptions$test != "none") { # && attr(x, "converged")) {
TEST <- blav_model_test(lavmodel = lavmodel,
lavpartable = lavpartable,
lavsamplestats = lavsamplestats,
lavoptions = lavoptions,
x = x,
VCOV = VCOV,
lavdata = lavdata,
lavcache = lavcache,
lavjags = lavjags,
lavobject = LAV,
samplls = samplls,
jagextra = mcmcextra,
stansumm = stansumm)
if(verbose) cat(" done.\n")
}
timing$TEST <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
# 9. collect information about model fit (S4)
lavfit <- blav_model_fit(lavpartable = lavpartable,
lavmodel = lavmodel,
lavjags = lavjags,
x = x,
VCOV = VCOV,
TEST = TEST)
## add SE and SD-Bayes factor to lavpartable
## (code around line 270 of blav_object_methods
## can be removed with this addition near line 923
## of lav_object_methods:
## if(object@Options$estimator == "Bayes") {
## LIST$logBF <- PARTABLE$logBF
## }
lavpartable$se <- lavfit@se[lavpartable$id]
## TODO fix this for stan
lavpartable$logBF <- rep(NA, length(lavpartable$se))
if(target == "jags"){
lavpartable$logBF <- SDBF(lavpartable)
}
## add monitors in mcmcextra as defined variables (except reserved monitors)
if(length(mcmcextra$monitor) > 0 & target != "stan"){
reservemons <- which(mcmcextra$monitor %in% c('deviance', 'pd', 'popt',
'dic', 'ped', 'full.pd', 'eta'))
if(length(reservemons) < length(mcmcextra$monitor)){
jecopy <- mcmcextra
if(length(reservemons) > 0) jecopy$monitor <- jecopy$monitor[-reservemons]
lavpartable <- add_monitors(lavpartable, lavjags, jecopy)
}
}
## 9b. move some stuff from lavfit to optim, for lavaan 0.5-21
## also create external slot
optnames <- c('x','npar','iterations','converged','fx','fx.group','logl.group',
'logl','control')
lavoptim <- lapply(optnames, function(x) slot(lavfit, x))
names(lavoptim) <- optnames
extslot <- list(mcmcout = lavjags, samplls = samplls,
origpt = lavpartable, inits = jagtrans$inits,
mcmcdata = jagtrans$data, pxpt = jagtrans$pxpartable,
burnin = burnin, sample = sample)
if(grepl("stan", target)){
extslot <- c(extslot, list(stansumm = stansumm))
if(save.lvs & target=="stan") extslot <- c(extslot, list(stanlvs = stanlvs))
}
if(jags.ic) extslot <- c(extslot, list(sampkls = sampkls))
if(save.lvs & !ordmod) {
extslot <- c(extslot, list(cfx = cfx, csamplls = csamplls))
if(jags.ic) extslot <- c(extslot, list(csampkls = csampkls))
}
## move total to the end
timing$total <- (proc.time()[3] - start.time0)
tt <- timing$total
timing <- timing[names(timing) != "total"]
timing <- c(timing, list(total = tt))
# 10. construct blavaan object
blavaan <- new("blavaan",
call = mc, # match.call
timing = timing, # list
Options = lavoptions, # list
ParTable = lavpartable, # list
pta = LAV@pta, # list
Data = lavdata, # S4 class
SampleStats = lavsamplestats, # S4 class
Model = lavmodel, # S4 class
Cache = lavcache, # list
Fit = lavfit, # S4 class
boot = list(),
optim = lavoptim,
implied = lavimplied, # list
vcov = lavvcov,
external = extslot,
test = TEST # copied for now
)
# post-fitting checks
if(attr(x, "converged")) {
lavInspect(blavaan, "post.check")
}
if(jag.do.fit & lavoptions$warn & !prisamp){
if(any(blavInspect(blavaan, 'neff') < 100)){
warning("blavaan WARNING: Small effective sample sizes (< 100) for some parameters.", call. = FALSE)
}
}
blavaan
}
## cfa + sem
bcfa <- bsem <- function(..., cp = "srs", dp = NULL,
n.chains = 3, burnin, sample, adapt,
mcmcfile = FALSE, mcmcextra = list(), inits = "prior",
convergence = "manual", target = "stan", save.lvs = FALSE, wiggle = NULL,
wiggle.sd = 0.1, prisamp = FALSE, jags.ic = FALSE, seed = NULL,
bcontrol = list()) {
dotdotdot <- list(...)
std.lv <- ifelse(any(names(dotdotdot) == "std.lv"), dotdotdot$std.lv, FALSE)
mc <- match.call()
mc$model.type = as.character( mc[[1L]] )
if(length(mc$model.type) == 3L) mc$model.type <- mc$model.type[3L]
mc$n.chains = n.chains
mc$int.ov.free = TRUE
mc$int.lv.free = FALSE
mc$auto.fix.first = !std.lv
mc$auto.fix.single = TRUE
mc$auto.var = TRUE
mc$auto.cov.lv.x = TRUE
mc$auto.cov.y = TRUE
mc$auto.th = TRUE
mc$auto.delta = TRUE
mc[[1L]] <- quote(blavaan)
## change defaults depending on jags vs stan
sampargs <- c("burnin", "sample", "adapt")
if(target == "jags"){
defiters <- c(4000L, 10000L, 1000L)
} else {
defiters <- c(500L, 1000L, 1000L)
}
suppargs <- which(!(sampargs %in% names(mc)))
if(length(suppargs) > 0){
for(i in 1:length(suppargs)){
mc[[(length(mc)+1)]] <- defiters[suppargs[i]]