Repository navigation
Expand file tree
/
Copy pathaFIPC.R
More file actions
1054 lines (965 loc) · 36.1 KB
/
Copy pathaFIPC.R
File metadata and controls
1054 lines (965 loc) · 36.1 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
#' automated fixed item parameter linking
#'
#' @import mirt
#' @param newformXData new form data X
#' @param oldformYData old form (base form) data Y
#' @param newformCommonItemNames Common item variable names in new form data
#' @param oldformCommonItemNames Common item variable names in old (base) form data
#' @param itemtype itemtype of calibration
#' @param newformBILOGprior using BILOG-MG prior when try to calibrate 3PL model? if you want, set the this to TRUE
#' @param oldformBILOGprior using BILOG-MG prior when try to calibrate 3PL model? if you want, set the this to TRUE
#' @param tryFitwholeNewItems do you want to try calibrate new form data? default is TRUE
#' @param tryFitwholeOldItems do you want to try calibrate base form data? default is TRUE
#' @param checkIPD do you want to check item parameter drift? default is TRUE
#' @param tryEM do you want to try EM algorithm when you calibrate model? defalut is TRUE
#' @param freeMEAN allow freely mean estimation, default is TRUE
#' @param forceNormalZeroOne set the prior distribution follows N(0,1) distribution. default is FALSE
#' @param parameterOverwrite don't touch it
#' @param empiricalhist do you want to use empirical histogram method when tryEM = TRUE? default is FALSE
#' @param confirmCommonItems set TRUE to accept the supplied common-item pairs without an interactive prompt. Default NULL: in interactive sessions the user will be prompted; set FALSE to explicitly reject (function will stop).
#' @param ... Additional arguments reserved for future extensions.
#'
#' @return the model list of the base form, new form, linked form
#' @export
#'
#' @examples
#' \dontrun{
#' autoFIPC(
#' newformXData = new_model,
#' oldformYData = old_model,
#' newformCommonItemNames = common_new,
#' oldformCommonItemNames = common_old,
#' confirmCommonItems = TRUE
#' )
#' }
autoFIPC <-
function(
newformXData,
oldformYData,
newformCommonItemNames,
oldformCommonItemNames,
itemtype = '3PL',
newformBILOGprior = NULL,
oldformBILOGprior = NULL,
tryFitwholeNewItems = T,
tryFitwholeOldItems = T,
checkIPD = T,
tryEM = T,
freeMEAN = T,
forceNormalZeroOne = F,
parameterOverwrite = F,
empiricalhist = F,
confirmCommonItems = NULL,
...
) {
# print credits
message('automated Fixed Item Parameter Calibration: aFIPC 0.2')
message('Seongho Bae (seongho@kw.ac.kr)\n')
try(invisible(gc()), silent = T)
# garbage cleaning
# Input validation - Security Enhancement
isRealMirtModel <- function(x) {
if (!isS4(x) || !methods::is(x, "SingleGroupClass")) return(FALSE)
ok <- tryCatch({
vals <- mirt::mod2values(x)
is.data.frame(vals) || is.matrix(vals)
}, error = function(e) FALSE, warning = function(w) FALSE)
if (!isTRUE(ok)) return(FALSE)
required_slots <- c("OptimInfo", "ParObjects")
return(all(required_slots %in% methods::slotNames(x)))
}
if (!is.data.frame(newformXData) && !is.matrix(newformXData) && !isRealMirtModel(newformXData)) {
stop("Security Error: newformXData must be a data.frame, matrix, or a valid fitted mirt model")
}
if (!is.data.frame(oldformYData) && !is.matrix(oldformYData) && !isRealMirtModel(oldformYData)) {
stop("Security Error: oldformYData must be a data.frame, matrix, or a valid fitted mirt model")
}
if (!is.character(newformCommonItemNames) && !is.factor(newformCommonItemNames)) {
stop("Security Error: newformCommonItemNames must be a character vector")
}
if (!is.character(oldformCommonItemNames) && !is.factor(oldformCommonItemNames)) {
stop("Security Error: oldformCommonItemNames must be a character vector")
}
if (!is.character(itemtype)) stop('Security Error: itemtype must be a character vector')
nItems <- NA_integer_
if (is.data.frame(newformXData) || is.matrix(newformXData)) nItems <- ncol(as.data.frame(newformXData))
else if (is.data.frame(oldformYData) || is.matrix(oldformYData)) nItems <- ncol(as.data.frame(oldformYData))
if (!is.na(nItems) && !(length(itemtype) == 1 || length(itemtype) == nItems)) stop(sprintf('Security Error: itemtype must be length 1 or length %d (number of items).', nItems))
# boolean parameter validation
if (!is.null(newformBILOGprior) && (!is.logical(newformBILOGprior) || length(newformBILOGprior) != 1 || is.na(newformBILOGprior))) stop("Security Error: newformBILOGprior must be a single non-NA logical value or NULL")
if (!is.null(oldformBILOGprior) && (!is.logical(oldformBILOGprior) || length(oldformBILOGprior) != 1 || is.na(oldformBILOGprior))) stop("Security Error: oldformBILOGprior must be a single non-NA logical value or NULL")
if (!is.null(confirmCommonItems) && (!is.logical(confirmCommonItems) || length(confirmCommonItems) != 1 || is.na(confirmCommonItems))) stop("Security Error: confirmCommonItems must be a single non-NA logical value or NULL")
if (!is.logical(tryFitwholeNewItems) || length(tryFitwholeNewItems) != 1 || is.na(tryFitwholeNewItems)) stop("Security Error: tryFitwholeNewItems must be a single non-NA logical value")
if (!is.logical(tryFitwholeOldItems) || length(tryFitwholeOldItems) != 1 || is.na(tryFitwholeOldItems)) stop("Security Error: tryFitwholeOldItems must be a single non-NA logical value")
if (!is.logical(checkIPD) || length(checkIPD) != 1 || is.na(checkIPD)) stop("Security Error: checkIPD must be a single non-NA logical value")
if (!is.logical(tryEM) || length(tryEM) != 1 || is.na(tryEM)) stop("Security Error: tryEM must be a single non-NA logical value")
if (!is.logical(freeMEAN) || length(freeMEAN) != 1 || is.na(freeMEAN)) stop("Security Error: freeMEAN must be a single non-NA logical value")
if (!is.logical(forceNormalZeroOne) || length(forceNormalZeroOne) != 1 || is.na(forceNormalZeroOne)) stop("Security Error: forceNormalZeroOne must be a single non-NA logical value")
if (!is.logical(parameterOverwrite) || length(parameterOverwrite) != 1 || is.na(parameterOverwrite)) stop("Security Error: parameterOverwrite must be a single non-NA logical value")
if (!is.logical(empiricalhist) || length(empiricalhist) != 1 || is.na(empiricalhist)) stop("Security Error: empiricalhist must be a single non-NA logical value")
# checking configure
if (length(newformCommonItemNames) != length(oldformCommonItemNames)) {
stop('Common Items are not equal')
}
if (
length(newformCommonItemNames) == 0 |
length(oldformCommonItemNames) == 0
) {
stop('Please provide common item names')
}
# checking common items
message('Checking correspond common item names')
to <- rep("<<<", length(newformCommonItemNames))
print(data.frame(cbind(
newformCommonItemNames,
to,
oldformCommonItemNames
)))
correspondItems <-
data.frame(cbind(newformCommonItemNames, oldformCommonItemNames))
checkCorrect <- function() {
if (isTRUE(confirmCommonItems)) {
return(1L)
}
if (identical(confirmCommonItems, FALSE)) {
return(2L)
}
if (!interactive()) {
stop(
'Common item confirmation requires an interactive session; ',
'set confirmCommonItems = TRUE to accept the supplied pairs.'
)
}
for (attempt in seq_len(3)) {
n <- readline(prompt = "Is it correct? (1: Yes 2: No) : ")
if (grepl("^[0-9]+$", n)) {
return(as.integer(n))
}
}
stop("Too many invalid common item confirmation attempts")
}
confirm <- checkCorrect()
if (confirm != 1) {
stop('Please write down pairs correctly')
}
# estimate models for calibration
if (
!is.data.frame(oldformYData) &&
!is.matrix(oldformYData)
) {
# if Data is mirt model
oldFormModel <- oldformYData
oldformYDataK <- data.frame(oldFormModel@Data$data)
} else {
# if Data is data.frame
oldformYDataK <- oldformYData
if (itemtype == '3PL' && length(oldformBILOGprior) == 0) {
checkoldformBILOGprior <- function() {
if (!interactive()) stop("Interactive session required for oldform BILOG prior")
for (attempt in seq_len(3)) {
n <-
readline(
prompt = "Do you want to use default BILOG-MG priors for oldform Data? (1: Yes 2: No) : "
)
if (grepl("^[0-9]+$", n)) {
return(as.integer(n))
}
}
stop("Too many invalid oldform BILOG prior attempts")
}
oldformBILOGprior <- checkoldformBILOGprior()
if (oldformBILOGprior == 1) {
oldformBILOGprior <- TRUE
} else {
oldformBILOGprior <- FALSE
}
}
message('\nestimating oldForm (Y) parameters')
if (itemtype == '3PL' && oldformBILOGprior == T) {
message('with traditional MMLE/EM approach')
oldFormModelSyntax <-
mirt::mirt.model(
paste0(
'F1 = 1-',
ncol(oldformYData),
'\n',
'PRIOR = (1-',
ncol(oldformYData),
', a1, lnorm, 1, 1.6487), ',
'(1-',
ncol(oldformYData),
', g, norm, .22, .08)'
)
)
try(
oldFormModel <-
mirt::mirt(
data = oldformYData,
model = oldFormModelSyntax,
itemtype = itemtype,
SE = T,
accelerate = 'squarem'
)
)
} else {
# try to search priors automatically. if it fail, try to bayesian approaches
message(
'with estimate prior distribution using an empirical histogram approach. please be patient.'
)
try(
oldFormModel <-
mirt::mirt(
data = oldformYData,
model = 1,
itemtype = itemtype,
SE = T,
accelerate = 'squarem',
empiricalhist = T,
technical = list(NCYCLES = 1e+5),
GenRandomPars = F
)
)
}
if (!exists("oldFormModel", inherits = FALSE)) {
stop("Security Error: Initial estimation of oldFormModel completely failed")
}
if (tryFitwholeOldItems == T) {
if (
(!exists("oldFormModel", inherits = FALSE)) || (!isTRUE(oldFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. estimating new parameters with no prior distribution using quasi-Monte Carlo EM estimation. please be patient.'
)
try(rm(oldFormModel))
try(
oldFormModel <-
mirt::mirt(
data = oldformYDataK,
1,
itemtype = itemtype,
SE = T,
method = 'QMCEM',
accelerate = 'squarem',
technical = list(NCYCLES = 1e+5),
GenRandomPars = F
)
)
}
if (
(!exists("oldFormModel", inherits = FALSE)) || (!isTRUE(oldFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. estimating new parameters with no prior distribution using Cai\'s (2010) Metropolis-Hastings Robbins-Monro (MHRM) algorithm. please be patient.'
)
try(rm(oldFormModel), silent = TRUE)
for (attempt in seq_len(3)) {
try(
oldFormModel <-
mirt::mirt(
data = oldformYDataK,
1,
itemtype = itemtype,
SE = T,
method = 'MHRM',
accelerate = 'squarem',
technical = list(NCYCLES = 1e+5, MHRM_SE_draws = 200000),
GenRandomPars = F
)
)
if (exists('oldFormModel', inherits = FALSE)) break
}
if (!exists('oldFormModel', inherits = FALSE)) stop('Failed to estimate oldFormModel with MHRM after 3 attempts')
}
}
if (
(!exists("oldFormModel", inherits = FALSE)) || (!isTRUE(oldFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. trying to remove weird items by itemfit statistics'
)
try(rm(oldFormModel))
oldFormModel <-
surveyFA(
oldformYData,
autofix = F,
SE = T,
forceUIRT = T
)
}
if (
(!exists("oldFormModel", inherits = FALSE)) || (!isTRUE(oldFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. trying to remove weird items by itemfit statistics by normal MMLE/EM'
)
try(rm(oldFormModel))
oldFormModel <-
surveyFA(
oldformYData,
autofix = F,
SE = T,
forceUIRT = T,
forceNormalEM = T
)
}
if (
(!exists("oldFormModel", inherits = FALSE)) || (!isTRUE(oldFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. trying to remove weird items by itemfit statistics by MMLE/QMCEM'
)
try(rm(oldFormModel))
oldFormModel <-
surveyFA(
oldformYData,
autofix = F,
SE = T,
forceUIRT = T,
unstable = T
)
}
if (
(!exists("oldFormModel", inherits = FALSE)) || (!isTRUE(oldFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. trying to remove weird items by itemfit statistics by MMLE/MHRM'
)
try(rm(oldFormModel))
oldFormModel <-
surveyFA(
oldformYData,
autofix = F,
SE = T,
forceUIRT = T,
forceMHRM = T
)
}
if (
(!exists("oldFormModel", inherits = FALSE)) || (!isTRUE(oldFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
stop('Estimation failed. Please check test quality.')
}
}
if (
!is.data.frame(newformXData) &&
!is.matrix(newformXData)
) {
# if Data is mirt model
newFormModel <- newformXData
newformXDataK <- data.frame(newFormModel@Data$data)
} else {
newformXDataK <- newformXData
if (itemtype == '3PL' && length(newformBILOGprior) == 0) {
checknewformBILOGprior <- function() {
if (!interactive()) stop("Interactive session required for newform BILOG prior")
for (attempt in seq_len(3)) {
n <-
readline(
prompt = "Do you want to use default BILOG-MG priors for newform Data? (1: Yes 2: No) : "
)
if (grepl("^[0-9]+$", n)) {
return(as.integer(n))
}
}
stop("Too many invalid newform BILOG prior attempts")
}
newformBILOGprior <- checknewformBILOGprior()
if (newformBILOGprior == 1) {
newformBILOGprior <- TRUE
} else {
newformBILOGprior <- FALSE
}
}
message('\nestimating newForm (X) parameters')
if (itemtype == '3PL' && newformBILOGprior == T) {
message('with traditional MMLE/EM approach')
newFormModelSyntax <-
mirt::mirt.model(
paste0(
'F1 = 1-',
ncol(newformXData),
'\n',
'PRIOR = (1-',
ncol(newformXData),
', a1, lnorm, 1, 1.6487), ',
'(1-',
ncol(newformXData),
', g, norm, .22, .08)'
)
)
try(
newFormModel <-
mirt::mirt(
data = newformXData,
model = newFormModelSyntax,
itemtype = itemtype,
SE = T,
accelerate = 'squarem'
)
)
} else {
message(
'with estimate prior distribution using an empirical histogram approach. please be patient.'
)
try(
newFormModel <-
mirt::mirt(
data = newformXDataK,
1,
itemtype = itemtype,
SE = T,
empiricalhist = T,
accelerate = 'squarem',
technical = list(NCYCLES = 1e+5),
GenRandomPars = F
)
)
}
if (!exists("newFormModel", inherits = FALSE)) {
stop("Security Error: Initial estimation of newFormModel completely failed")
}
if (tryFitwholeNewItems) {
if (
(!exists("newFormModel", inherits = FALSE)) || (!isTRUE(newFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. estimating new parameters with no prior distribution using quasi-Monte Carlo EM estimation. please be patient.'
)
try(rm(newFormModel))
try(
newFormModel <-
mirt::mirt(
data = newformXDataK,
1,
itemtype = itemtype,
SE = T,
method = 'QMCEM',
accelerate = 'squarem',
technical = list(NCYCLES = 1e+5),
GenRandomPars = F
)
)
}
if (
(!exists("newFormModel", inherits = FALSE)) || (!isTRUE(newFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. estimating new parameters with no prior distribution using Cai\'s (2010) Metropolis-Hastings Robbins-Monro (MHRM) algorithm. please be patient.'
)
try(rm(newFormModel), silent = TRUE)
for (attempt in seq_len(3)) {
try(
newFormModel <-
mirt::mirt(
data = newformXDataK,
1,
itemtype = itemtype,
SE = T,
method = 'MHRM',
accelerate = 'squarem',
technical = list(NCYCLES = 1e+5, MHRM_SE_draws = 200000),
GenRandomPars = F
)
)
if (exists('newFormModel', inherits = FALSE)) break
}
if (!exists('newFormModel', inherits = FALSE)) stop('Failed to estimate newFormModel with MHRM after 3 attempts')
}
}
if (
(!exists("newFormModel", inherits = FALSE)) || (!isTRUE(newFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. trying to remove weird items by itemfit statistics'
)
try(rm(newFormModel))
newFormModel <-
surveyFA(
newformXData,
autofix = F,
SE = T,
forceUIRT = T
)
}
if (
(!exists("newFormModel", inherits = FALSE)) || (!isTRUE(newFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. trying to remove weird items by itemfit statistics again by normal MMLE/EM'
)
try(rm(newFormModel))
newFormModel <-
surveyFA(
newformXData,
autofix = F,
SE = T,
forceUIRT = T,
forceNormalEM = T
)
}
if (
(!exists("newFormModel", inherits = FALSE)) || (!isTRUE(newFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. trying to remove weird items by itemfit statistics again by MMLE/QMCEM'
)
try(rm(newFormModel))
newFormModel <-
surveyFA(
newformXData,
autofix = F,
SE = T,
forceUIRT = T,
unstable = T
)
}
if (
(!exists("newFormModel", inherits = FALSE)) || (!isTRUE(newFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
message(
'Estimation failed. trying to remove weird items by itemfit statistics again by MMLE/MHRM'
)
try(rm(newFormModel))
newFormModel <-
surveyFA(
newformXData,
autofix = F,
SE = T,
forceUIRT = T,
forceMHRM = T
)
}
if (
(!exists("newFormModel", inherits = FALSE)) || (!isTRUE(newFormModel@OptimInfo$secondordertest) &&
itemtype != 'ideal')
) {
stop('Estimation failed. Please check test quality.')
}
}
# do FIPC
NewScaleParms <- mirt::mod2values(newFormModel)
OldScaleParms <- mirt::mod2values(oldFormModel)
# Preserve mirt's structural estimability flags. Forcing every row TRUE
# frees boundary parameters such as 2PL g/u and makes the Hessian unstable.
NewScaleParms$est[NewScaleParms$item == 'GROUP'] <- FALSE
OldScaleParms$est[OldScaleParms$item == 'GROUP'] <- FALSE
NewScaleParms$est[NewScaleParms$name == "COV_11"] <- TRUE
OldScaleParms$est[OldScaleParms$name == "COV_11"] <- TRUE
if (itemtype == 'Rasch') {
NewScaleParms$est[NewScaleParms$name == "a1"] <- FALSE
OldScaleParms$est[OldScaleParms$name == "a1"] <- FALSE
}
#IPD
if (checkIPD == T) {
# config
IPDgroup <-
as.factor(c(
rep('oldForm', nrow(oldformYDataK)),
rep('newForm', nrow(newformXDataK))
))
IPDItemCount <- 0
# IPD target item checking
newFormColNames <- colnames(newformXDataK[colnames(newFormModel@Data$data)])
oldFormColNames <- colnames(oldformYDataK[colnames(oldFormModel@Data$data)])
# ⚡ Bolt: Vectorized match() to avoid dynamic array growth overhead inside a for loop
idxNew <- match(newformCommonItemNames, newFormColNames)
idxOld <- match(oldformCommonItemNames, oldFormColNames)
valid_idx <- !is.na(idxNew) & !is.na(idxOld)
IPDItemNamesNewForm <- newFormColNames[idxNew[valid_idx]]
IPDItemNamesOldForm <- oldFormColNames[idxOld[valid_idx]]
IPDItemCount <- length(IPDItemNamesNewForm)
# IPD Data generation
IPDItemList <-
data.frame(rbind(IPDItemNamesOldForm, IPDItemNamesNewForm))
IPDData <-
data.frame(matrix(nrow = length(IPDgroup), ncol = IPDItemCount))
colnames(IPDData) <- paste0('X', 1:IPDItemCount)
print(IPDItemNamesOldForm)
print(IPDItemNamesNewForm)
IPDData[1:nrow(oldformYDataK), ] <-
oldformYDataK[, IPDItemNamesOldForm]
IPDData[nrow(oldformYDataK) + 1:nrow(newformXDataK), ] <-
newformXDataK[, IPDItemNamesNewForm]
# IPD estimation
IPDParmNames <- OldScaleParms$name
IPDParmNames <- IPDParmNames[!duplicated(IPDParmNames)]
IPDParmNames <- IPDParmNames[!grepl("^(MEAN|COV|ak|d0$)", IPDParmNames)]
IPDParmNames <- as.character(IPDParmNames)
mirt::mirtCluster()
message('Discovering IPD')
if (itemtype == 'nominal' | tryEM == T) {
if (empiricalhist == T) {
modIPD_MG <- mirt::multipleGroup(
IPDData,
model = 1,
group = IPDgroup,
itemtype = itemtype,
method = 'EM',
invariance = c(names(IPDData), 'free_means', 'free_var'),
empiricalhist = T,
technical = list(NCYCLES = 1e+5, removeEmptyRows = TRUE)
)
try(
modIPD_DIF <-
mirt::DIF(
modIPD_MG,
IPDParmNames,
scheme = 'drop_sequential',
method = 'EM',
empiricalhist = T,
technical = list(NCYCLES = 1e+5)
)
)
} else {
modIPD_MG <- mirt::multipleGroup(
IPDData,
model = 1,
group = IPDgroup,
itemtype = itemtype,
method = 'EM',
invariance = c(names(IPDData), 'free_means', 'free_var'),
empiricalhist = F,
technical = list(NCYCLES = 1e+5, removeEmptyRows = TRUE)
)
try(
modIPD_DIF <-
mirt::DIF(
modIPD_MG,
IPDParmNames,
scheme = 'drop_sequential',
method = 'EM',
empiricalhist = F,
technical = list(NCYCLES = 1e+5)
)
)
}
} else {
modIPD_MG <- mirt::multipleGroup(
IPDData,
model = 1,
group = IPDgroup,
itemtype = itemtype,
method = 'MHRM',
invariance = c(names(IPDData), 'free_means', 'free_var'),
technical = list(NCYCLES = 1e+5, removeEmptyRows = TRUE)
)
try(
modIPD_DIF <-
mirt::DIF(
modIPD_MG,
IPDParmNames,
scheme = 'drop_sequential',
method = 'MHRM',
technical = list(NCYCLES = 1e+5)
)
)
}
mirt::mirtCluster(remove = T)
if (exists('modIPD_DIF', inherits = FALSE)) {
modIPD_IPDItem <- names(modIPD_DIF)
CommonItemList_NOIPD <-
colnames(IPDData)[!colnames(IPDData) %in% modIPD_IPDItem]
print(modIPD_DIF)
print(CommonItemList_NOIPD)
# ⚡ Bolt: 루프 내에서 데이터 프레임을 서브셋팅(subsetting)하는 O(N) 연산을
# unlist()를 활용한 벡터화된(vectorized) O(1) 연산으로 대체하여 성능 향상
ActualoldFormCommonItem <-
as.character(unlist(IPDItemList[1, CommonItemList_NOIPD]))
ActualnewFormCommonItem <-
as.character(unlist(IPDItemList[2, CommonItemList_NOIPD]))
message('ActualoldFormCommonItem: ', ActualoldFormCommonItem)
message('ActualnewFormCommonItem: ', ActualnewFormCommonItem)
oldformCommonItemNames <- ActualoldFormCommonItem
newformCommonItemNames <- ActualnewFormCommonItem
message('oldformCommonItemNames: ', ActualoldFormCommonItem)
message('newformCommonItemNames: ', ActualnewFormCommonItem)
} else {
message('No IPD detected')
}
}
newFormColNames <- colnames(newformXDataK[colnames(newFormModel@Data$data)])
oldFormColNames <- colnames(oldformYDataK[colnames(oldFormModel@Data$data)])
# ⚡ Bolt: Cache parameter indices to avoid O(N) linear search inside loop
newScaleParmsItemIdxCache <- split(seq_len(nrow(NewScaleParms)), NewScaleParms$item)
oldScaleParmsItemIdxCache <- split(seq_len(nrow(OldScaleParms)), OldScaleParms$item)
# ⚡ Bolt: Vectorize match() outside the loop to avoid repeated array scanning overhead
idxNew_all <- match(newformCommonItemNames, newFormColNames)
idxOld_all <- match(oldformCommonItemNames, oldFormColNames)
for (i in seq_along(oldformCommonItemNames)) {
newFormItemStr <- newformCommonItemNames[i]
oldFormItemStr <- oldformCommonItemNames[i]
newFormItemName <- newFormColNames[idxNew_all[i]]
oldFormItemName <- oldFormColNames[idxOld_all[i]]
if (
!is.na(newFormItemName) &&
!is.na(oldFormItemName) &&
(length(stats::na.omit(unique(newFormModel@Data$data[, newFormItemName]))) ==
length(stats::na.omit(unique(oldFormModel@Data$data[, oldFormItemName]))))
) {
message(
'applying ',
newFormItemStr,
' <<< ',
oldFormItemStr,
' as common item use'
)
# ⚡ Bolt: Use cached O(1) dictionary lookups instead of O(N) which() scans
newIdx <- newScaleParmsItemIdxCache[[newFormItemStr]]
oldIdx <- oldScaleParmsItemIdxCache[[oldFormItemStr]]
# ⚡ Bolt: Remove unnecessary paste0() array string generation overhead
message(' Newform Parms: ', paste(NewScaleParms$value[newIdx], collapse = ' '))
message(' Oldform Parms: ', paste(OldScaleParms$value[oldIdx], collapse = ' '))
NewScaleParms$value[newIdx] <-
OldScaleParms$value[oldIdx]
message(' Linkedform Parms: ', paste(NewScaleParms$value[newIdx], collapse = ' '), '\n')
NewScaleParms$est[newIdx] <-
FALSE
} else {
message(
'skipping ',
newFormItemStr,
' <<< ',
oldFormItemStr,
' as common item use'
)
}
}
if (
length(attr(newFormModel@ParObjects$lrPars, 'parnum')) != 0 &&
length(attr(oldFormModel@ParObjects$lrPars, 'parnum')) != 0
) {
newBetaIdx <- NewScaleParms$item == 'BETA'
oldBetaIdx <- OldScaleParms$item == 'BETA'
NewScaleParms$value[newBetaIdx] <-
OldScaleParms$value[oldBetaIdx]
NewScaleParms$est[newBetaIdx] <-
FALSE
message('applying BETA parameter as linking')
message(
' Linkedform Parms: ',
paste0(
NewScaleParms$value[newBetaIdx],
' '
),
'\n'
)
betaFormula <-
attr(newFormModel@ParObjects$lrPars, 'formula')[[1]]
betaCOVdata <- attr(newFormModel@ParObjects$lrPars, 'df')
betaSE <- FALSE
betaEmpiricalhist <- FALSE
} else if (empiricalhist == F) {
betaFormula <- NULL
betaCOVdata <- NULL
betaSE <- TRUE
betaEmpiricalhist <- FALSE
} else {
betaFormula <- NULL
betaCOVdata <- NULL
betaSE <- TRUE
betaEmpiricalhist <- TRUE
}
message('\nestimating Linked Form Eq(X) parameters')
# ⚡ Bolt: Cache subsetted dataframe to avoid repeated O(N) memory copies during mirt model setup
linkedFormData <- newformXDataK[colnames(newFormModel@Data$data)]
if (forceNormalZeroOne) {
freeMEAN <- F
new_cov11_idx <- NewScaleParms$name == "COV_11"
old_cov11_idx <- OldScaleParms$name == "COV_11"
new_mean11_idx <- NewScaleParms$name == "MEAN_11"
old_mean11_idx <- OldScaleParms$name == "MEAN_11"
NewScaleParms$est[new_cov11_idx] <- FALSE
OldScaleParms$est[old_cov11_idx] <- FALSE
NewScaleParms$est[new_mean11_idx] <- FALSE
OldScaleParms$est[old_mean11_idx] <- FALSE
NewScaleParms$value[new_cov11_idx] <- 1
OldScaleParms$value[old_mean11_idx] <- 0
}
if (freeMEAN == T) {
LinkedModelSyntax <-
mirt::mirt.model(paste0(
'F1 = 1-',
ncol(linkedFormData),
'\n',
'MEAN = F1'
))
NewScaleParms$est[NewScaleParms$name == "MEAN_1"] <- TRUE
OldScaleParms$est[OldScaleParms$name == "MEAN_1"] <- TRUE
} else {
LinkedModelSyntax <-
mirt::mirt.model(paste0(
'F1 = 1-',
ncol(linkedFormData),
'\n'
))
}
print(NewScaleParms)
if (itemtype == 'nominal' | tryEM == T) {
if (betaEmpiricalhist) {
message(
'with MMLE/EM + empirical histogram approach. please be patient.'
)
} else {
message('with MMLE/EM approach. please be patient.')
}
if (sum(NewScaleParms$est) == 0) {
# LinkedModel <- oldFormModel
LinkedModel <-
mirt::mirt(
data = linkedFormData,
LinkedModelSyntax,
itemtype = newFormModel@Model$itemtype,
method = 'EM',
SE = F,
accelerate = 'squarem',
empiricalhist = betaEmpiricalhist,
technical = list(
NCYCLES = 1e+6,
SEtol = 1e-4,
MHRM_SE_draws = 1e+5
),
pars = NewScaleParms,
GenRandomPars = F,
covdata = betaCOVdata,
formula = betaFormula
)
} else {
LinkedModel <-
mirt::mirt(
data = linkedFormData,
LinkedModelSyntax,
itemtype = newFormModel@Model$itemtype,
method = 'EM',
SE = betaSE,
accelerate = 'squarem',
empiricalhist = betaEmpiricalhist,
technical = list(
NCYCLES = 1e+6,
SEtol = 1e-4,
MHRM_SE_draws = 1e+5
),
pars = NewScaleParms,
GenRandomPars = F,
covdata = betaCOVdata,
formula = betaFormula
)
}
} else {
message(
'with Cai\'s (2010) Metropolis-Hastings Robbins-Monro (MHRM) approach. please be patient.'
)
if (sum(NewScaleParms$est) == 0) {
# LinkedModel <- oldFormModel
LinkedModel <-
mirt::mirt(
data = linkedFormData,
LinkedModelSyntax,
itemtype = newFormModel@Model$itemtype,
method = 'MHRM',
SE = F,
accelerate = 'squarem',
TOL = .0005,
technical = list(
NCYCLES = 1e+6,
SEtol = 1e-4,
MHRM_SE_draws = 1e+5
),
pars = NewScaleParms,
GenRandomPars = F,
covdata = betaCOVdata,
formula = betaFormula
)
} else {
LinkedModel <-
mirt::mirt(
data = linkedFormData,
LinkedModelSyntax,
itemtype = newFormModel@Model$itemtype,
method = 'MHRM',
SE = betaSE,
accelerate = 'squarem',
TOL = .0005,
technical = list(
NCYCLES = 1e+6,
SEtol = 1e-4,
MHRM_SE_draws = 1e+5
),
pars = NewScaleParms,
GenRandomPars = F,
covdata = betaCOVdata,
formula = betaFormula
)
}
}
# if(!LinkedModel@OptimInfo$secondordertest){
# message('Estimation failed. estimating new parameters with no prior distribution using quasi-Monte Carlo EM estimation. please be patient.')
#
# rm(LinkedModel)
# try(LinkedModel <- mirt::mirt(data = linkedFormData, LinkedModelSyntax, itemtype = newFormModel@Model$itemtype, SE = T, method = 'QMCEM', accelerate = 'squarem', technical = list(NCYCLES = 1e+5), pars = NewScaleParms, GenRandomPars = F))
# }
#
# if(!LinkedModel@OptimInfo$secondordertest){
# message('Estimation failed. estimating new parameters with no prior distribution using Cai\'s (2010) Metropolis-Hastings Robbins-Monro (MHRM) algorithm. please be patient.')
#