-
Notifications
You must be signed in to change notification settings - Fork 21
/
studentGrowthPercentiles.R
1954 lines (1757 loc) · 111 KB
/
studentGrowthPercentiles.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
`studentGrowthPercentiles` <-
function(panel.data, ## REQUIRED
sgp.labels, ## REQUIRED
panel.data.vnames=NULL,
additional.vnames.to.return=NULL,
grade.progression,
content_area.progression=NULL,
year.progression=NULL,
year_lags.progression=NULL,
num.prior,
max.order.for.percentile=NULL,
return.additional.max.order.sgp=NULL,
subset.grade,
percentile.cuts=NULL,
growth.levels,
use.my.knots.boundaries,
use.my.coefficient.matrices=NULL,
calculate.confidence.intervals=NULL,
print.other.gp=FALSE,
print.sgp.order=FALSE,
calculate.sgps=TRUE,
rq.method="br",
rq.method.for.large.n="fn",
max.n.for.coefficient.matrices=NULL,
knot.cut.percentiles=c(0.2,0.4,0.6,0.8),
knots.boundaries.by.panel=FALSE,
exact.grade.progression.sequence=FALSE,
drop.nonsequential.grade.progression.variables=TRUE,
convert.0and100=TRUE,
sgp.quantiles="Percentiles",
sgp.quantiles.labels=NULL,
sgp.loss.hoss.adjustment=NULL,
sgp.cohort.size=NULL,
sgp.less.than.sgp.cohort.size.return=NULL,
sgp.test.cohort.size=NULL,
percuts.digits=0L,
isotonize=TRUE,
convert.using.loss.hoss=TRUE,
goodness.of.fit=TRUE,
goodness.of.fit.minimum.n=NULL,
goodness.of.fit.output.format="GROB",
return.prior.scale.score=TRUE,
return.prior.scale.score.standardized=TRUE,
return.norm.group.identifier=TRUE,
return.norm.group.scale.scores=NULL,
return.norm.group.dates=NULL,
return.norm.group.preference=NULL,
return.panel.data=identical(parent.frame(), .GlobalEnv),
print.time.taken=TRUE,
parallel.config=NULL,
calculate.simex=NULL,
sgp.percentiles.set.seed=314159,
sgp.percentiles.equated=NULL,
SGPt=NULL,
SGPt.max.time=NULL,
verbose.output=FALSE) {
started.at <- proc.time()
started.date <- prettyDate()
##########################################################
###
### Internal utility functions
###
##########################################################
.smooth.bound.iso.row <- function(tmp.dt, iso=isotonize, sgp.loss.hoss.adjustment) {
X <- NULL
if (!is.null(sgp.loss.hoss.adjustment)) {
my.path.knots.boundaries <- get.my.knots.boundaries.path(sgp.labels[['my.subject']], as.character(sgp.labels[['my.year']]))
bnd <- eval(parse(text=paste0("Knots_Boundaries", my.path.knots.boundaries, "[['loss.hoss_", tmp.last, "']]")))
tmp.dt[X < bnd[1L], X:=bnd[1L]]
tmp.dt[X > bnd[2L], X:=bnd[2L]]
}
if (iso) setkey(tmp.dt, ID, X)
return(tmp.dt[['X']])
}
.create.path <- function(labels, pieces=c("my.subject", "my.year", "my.extra.label")) {
sub(' ', '_', toupper(sub('\\.+$', '', paste(unlist(lapply(labels[pieces], as.character)), collapse="."))))
}
.get.knots.boundaries <- function(data, by.grade) {
num.panels <- (dim(data)[2L]-1L)/2L
if (knots.boundaries.by.panel) {
tmp.years <- rep(yearIncrement(sgp.labels$my.year, (-num.panels+1L):-1L), each=dim(data)[1L])
} else {
tmp.years <- rep(sgp.labels$my.year, dim(data)[1L]*(num.panels-1L))
}
if (by.grade) {
tmp.grades <- unlist(data[,2L:(2L+num.panels-2L), with=FALSE], use.names=FALSE)
} else {
tmp.grades <- rep(head(tmp.gp, -1L), each=dim(data)[1L])
}
tmp.stack <- data.table(
VALID_CASE="VALID_CASE",
CONTENT_AREA=rep(head(content_area.progression, -1L), each=dim(data)[1L]),
GRADE=tmp.grades,
SCALE_SCORE=unlist(data[,(2L+num.panels):(2L+2*num.panels-2L), with=FALSE], use.names=FALSE),
YEAR=tmp.years, key=c("VALID_CASE", "CONTENT_AREA", "GRADE"))
createKnotsBoundaries(tmp.stack, knot.cut.percentiles)
}
.get.panel.data <- function(tmp.data, k, by.grade, tmp.gp) {
if (by.grade) {
if (is.character(tmp.gp)) tmp.gp.gpd <- shQuote(rev(tmp.gp)[seq(k+1L)]) else tmp.gp.gpd <- rev(tmp.gp)[seq(k+1L)]
eval(parse(text=paste0("na.omit(tmp.data[.(", paste(tmp.gp.gpd, collapse=", "), "), on=names(tmp.data)[c(", paste(1L+num.panels-(0:k), collapse=", ") , ")]], cols=names(tmp.data)[c(",paste(1L+2*num.panels-0:k, collapse=", "), ")])[,c(1, ", paste(rev(1+2*num.panels-0:k), collapse=", "), ")]")))
} else {
eval(parse(text=paste0("na.omit(tmp.data, cols=names(tmp.data)[c(",paste(1+2*num.panels-0:k, collapse=", "), ")])[,c(1, ", paste(rev(1L+2*num.panels-0:k), collapse=", "), ")]")))
}
}
get.my.knots.boundaries.path <- function(content_area, year) {
if (is.null(sgp.percentiles.equated)) {
tmp.knots.boundaries.names <-
names(Knots_Boundaries[[tmp.path.knots.boundaries]])[content_area==sapply(strsplit(names(Knots_Boundaries[[tmp.path.knots.boundaries]]), "[.]"), '[', 1L)]
if (length(tmp.knots.boundaries.names)==0L) {
return(paste0("[['", tmp.path.knots.boundaries, "']]"))
} else {
tmp.knots.boundaries.years <- sapply(strsplit(tmp.knots.boundaries.names, "[.]"), '[', 2L)
tmp.index <- sum(year >= tmp.knots.boundaries.years, na.rm=TRUE)
return(paste0("[['", tmp.path.knots.boundaries, "']][['", paste(c(content_area, sort(tmp.knots.boundaries.years)[tmp.index]), collapse="."), "']]"))
}
} else {
return(paste0("[['", tmp.path.knots.boundaries, "']][['", content_area, ".", sgp.percentiles.equated[['Year']], "']]"))
}
}
get.prior.cutscore.path <- function(content_area, year) {
if (is.null(sgp.percentiles.equated)) {
tmp.cutscores <- grep(content_area, names(SGP::SGPstateData[[goodness.of.fit]][['Achievement']][['Cutscores']]), value=TRUE)
if (length(tmp.cutscores) > 0L) {
tmp.cutscores.names <- tmp.cutscores[content_area==sapply(strsplit(tmp.cutscores, "[.]"), '[', 1L)]
tmp.cutscores.years <- sapply(strsplit(tmp.cutscores.names[grep(content_area, tmp.cutscores.names)], "[.]"), function(x) paste(x[-1L], collapse="."))
tmp.cutscores.years[tmp.cutscores.years==""]<-NA
tmp.sum <- sum(year >= sort(tmp.cutscores.years), na.rm=TRUE)
return(paste(c(content_area, sort(tmp.cutscores.years)[tmp.sum]), collapse="."))
} else return(content_area)
} else {
return(paste(content_area, sgp.percentiles.equated[['Year']], sep="."))
}
}
.create.coefficient.matrices <- function(data, k, by.grade, max.n.for.coefficient.matrices) {
rq.sgp <- function(..., my.taus) { # Function needs to be nested within the .create.coefficient.matrices function to avoid data copying with SNOW
if (rq.method == "br") {
tmp.res <- rq(method="br", ...)[['coefficients']]
} else {
tmp.res <- try(rq(method=rq.method, ...)[['coefficients']], silent=TRUE)
if (inherits(tmp.res, "try-error")) {
tmp.res <- rq(method="br", ...)[['coefficients']]
}
}
if (!is.matrix(tmp.res)) return(matrix(tmp.res, dimnames=list(names(tmp.res), paste("tau=", my.taus))))
return(tmp.res)
}
tmp.data <- .get.panel.data(data, k, by.grade, tmp.gp)
if (dim(tmp.data)[1L]==0L) return(NULL)
if (dim(tmp.data)[1L] < sgp.cohort.size) return("Insufficient N")
if (!is.null(max.n.for.coefficient.matrices) && dim(tmp.data)[1L] > max.n.for.coefficient.matrices) tmp.data <- tmp.data[sample(seq.int(dim(tmp.data)[1L]), max.n.for.coefficient.matrices)]
if (is.null(max.n.for.coefficient.matrices) && dim(tmp.data)[1L] >= 300000L) rq.method <- rq.method.for.large.n
tmp.num.variables <- dim(tmp.data)[2L]
mod <- character()
s4Ks <- "Knots=list("
s4Bs <- "Boundaries=list("
tmp.gp.iter <- rev(tmp.gp)[2L:(k+1L)]
for (i in seq_along(tmp.gp.iter)) {
my.path.knots.boundaries <- get.my.knots.boundaries.path(rev(content_area.progression)[i+1L], yearIncrement(rev(year.progression)[i+1L], 0L))
.check.knots.boundaries(names(eval(parse(text=paste0("Knots_Boundaries", my.path.knots.boundaries)))), tmp.gp.iter[i])
knt <- paste0("Knots_Boundaries", my.path.knots.boundaries, "[['knots_", tmp.gp.iter[i], "']]")
bnd <- paste0("Knots_Boundaries", my.path.knots.boundaries, "[['boundaries_", tmp.gp.iter[i], "']]")
mod <- paste0(mod, " + bs(tmp.data[[", tmp.num.variables-i, "]], knots=", knt, ", Boundary.knots=", bnd, ")")
s4Ks <- paste0(s4Ks, "knots_", tmp.gp.iter[i], "=", knt, ",")
s4Bs <- paste0(s4Bs, "boundaries_", tmp.gp.iter[i], "=", bnd, ",")
}
if (!is.null(SGPt)) {
tmp.data <- Panel_Data[,c("ID", "TIME", "TIME_LAG"), with=FALSE][tmp.data, on="ID"][,c(names(tmp.data), "TIME", "TIME_LAG"), with=FALSE]
mod <- paste0(mod, " + I(tmp.data[['TIME']]) + I(tmp.data[['TIME_LAG']])")
}
if (!is.null(tmp.par.config <- parallel.config)) if (is.null(parallel.config[["WORKERS"]][["TAUS"]])) tmp.par.config <- NULL
if (is.null(tmp.par.config)) {
tmp.mtx <- eval(parse(text=paste0("rq.sgp(tmp.data[[", tmp.num.variables, "]] ~ ", substring(mod,4), ", tau=taus, data=tmp.data, my.taus=taus)")))
} else {
par.start <- startParallel(tmp.par.config, 'TAUS', qr.taus=taus)
if (toupper(tmp.par.config[["BACKEND"]]) == "FOREACH") {
tmp.mtx <- foreach(x = iter(par.start$TAUS.LIST), .export=c("tmp.data", "Knots_Boundaries", "rq.method", "rq.sgp", "get.my.knots.boundaries.path"), .combine = "cbind", .errorhandling = "pass",
.inorder=TRUE, .options.mpi = par.start$foreach.options, .options.multicore = par.start$foreach.options, .options.snow = par.start$foreach.options) %dopar% {
eval(parse(text=paste0("rq.sgp(formula=tmp.data[[", tmp.num.variables, "]] ~ ", substring(mod,4), ", tau=x, data=tmp.data, my.taus=x)")))
}
if (any(!grepl("tau=", colnames(tmp.mtx)))) return(list(RQ_ERROR=unlist(tmp.mtx[,grep("tau=", colnames(tmp.mtx), invert=TRUE)][1L], use.names=FALSE)))
} else {
if (par.start$par.type == 'MULTICORE') {
tmp.mtx <- mclapply(par.start$TAUS.LIST, function(x) eval(parse(text=paste0("rq.sgp(tmp.data[[", tmp.num.variables, "]] ~ ",
substring(mod,4), ", tau=x, data=tmp.data, my.taus=x)"))), mc.cores=par.start$workers, mc.preschedule = FALSE)
if (any(tmp.tf <- sapply(tmp.mtx, function(x) inherits(x, "try-error")))) return(list(RQ_ERROR=sapply(which(tmp.tf), function(f) tmp.mtx[[f]][1L])))
tmp.mtx <- do.call(cbind, tmp.mtx)
}
if (par.start$par.type == 'SNOW') {
tmp.mtx <- parLapplyLB(par.start$internal.cl, par.start$TAUS.LIST, function(x) eval(parse(text=paste0("rq.sgp(tmp.data[[",
tmp.num.variables, "]] ~ ", substring(mod,4), ", tau=x, data=tmp.data, my.taus=x)"))))
if (any(tmp.tf <- sapply(tmp.mtx, function(x) inherits(x, "try-error")))) return(list(RQ_ERROR=sapply(which(tmp.tf), function(f) tmp.mtx[[f]][1L])))
tmp.mtx <- do.call(cbind, tmp.mtx)
}
}
stopParallel(tmp.par.config, par.start)
}
tmp.version <- list(
SGP_Package_Version=as.character(packageVersion("SGP")),
Date_Prepared=prettyDate(),
Matrix_Information=list(
N=dim(tmp.data)[1L],
Model=paste0("rq.sgp(tmp.data[[", tmp.num.variables, "]] ~ ", substring(mod,4), ", tau=taus, data=tmp.data, method=", rq.method, ")"),
SGPt=if (is.null(SGPt)) NULL else list(VARIABLES=unlist(SGPt), MAX_TIME=max(tmp.data$TIME, na.rm=TRUE), MAX_TIME_PRIOR=max(tmp.data$TIME-tmp.data$TIME_LAG, na.rm=TRUE), RANGE_TIME_LAG=range(tmp.data$TIME_LAG))))
eval(parse(text=paste0("new('splineMatrix', tmp.mtx, ", substring(s4Ks, 1L, nchar(s4Ks)-1L), "), ", substring(s4Bs, 1L, nchar(s4Bs)-1L), "), ",
"Content_Areas=list(as.character(tail(content_area.progression, k+1L))), ",
"Grade_Progression=list(as.character(tail(tmp.slot.gp, k+1L))), ",
"Time=list(as.character(tail(year.progression, k+1L))), ",
"Time_Lags=list(as.numeric(tail(year_lags.progression, k))), ",
"Version=tmp.version)")))
} ### END .create.coefficient.matrices
.check.knots.boundaries <- function(names, grade) {
tmp <- do.call(rbind, strsplit(names, "_"))
if (!grade %in% tmp[tmp[,1L]=="knots", 2L]) stop(paste0("knots_", grade, " not found in Knots_Boundaries."))
if (!grade %in% tmp[tmp[,1L]=="boundaries", 2L]) stop(paste0("boundaries_", grade, " not found in Knots_Boundaries."))
}
.create_taus <- function(sgp.quantiles) {
if (is.character(sgp.quantiles)) {
taus <- switch(sgp.quantiles,
PERCENTILES = (seq.int(100)-0.5)/100)
}
if (is.numeric(sgp.quantiles)) {
taus <- sgp.quantiles
}
return(taus)
}
get.coefficient.matrix.name <- function(tmp.last, k) {
return(paste0("qrmatrix_", tmp.last, "_", k))
}
.get.percentile.predictions <- function(my.data, my.matrix, SGPt.max.time=NULL) {
SCORE <- TIME <- TIME_LAG <- NULL
mod <- character()
for (k in seq_along(my.matrix@Time_Lags[[1L]])) {
knt <- paste0("my.matrix@Knots[[", k, "]]")
bnd <- paste0("my.matrix@Boundaries[[", k, "]]")
mod <- paste0(mod, ", bs(my.data[[", dim(my.data)[2L]-k, "]], knots=", knt, ", Boundary.knots=", bnd, ")")
}
if (!is.null(SGPt)) {
my.data <- Panel_Data[,c("ID", "TIME", "TIME_LAG"), with=FALSE][my.data, on="ID"][,c(names(my.data), "TIME", "TIME_LAG"), with=FALSE]
tmp.time.shift.index <- getTimeShiftIndex(max(as.numeric(my.data[['TIME']])), my.matrix)
if (max(my.data$TIME+365*-tmp.time.shift.index, na.rm=TRUE) > my.matrix@Version[['Matrix_Information']][['SGPt']][['MAX_TIME']]+30) stop("Matrix Misfit with TIME data!!!")
if (is.null(SGPt.max.time) && tmp.time.shift.index != 0) my.data[,TIME:=TIME+365*-tmp.time.shift.index]
if (!is.null(SGPt.max.time)) {
my.data[,TIME_LAG:=TIME_LAG+my.matrix@Version[['Matrix_Information']][['SGPt']][['MAX_TIME']]-(TIME+365*-tmp.time.shift.index)]
my.data[,TIME:=my.matrix@Version[['Matrix_Information']][['SGPt']][['MAX_TIME']]]
}
mod <- paste0(mod, ", my.data[['TIME']], my.data[['TIME_LAG']]")
}
tmp <- eval(parse(text=paste0("cbind(1L, ", substring(mod, 2L), ") %*% my.matrix")))
return(round(matrix(.smooth.bound.iso.row(data.table(ID=rep(seq.int(dim(tmp)[1L]), each=length(taus)), X=c(t(tmp))), isotonize, sgp.loss.hoss.adjustment), ncol=length(taus), byrow=TRUE), digits=5L))
}
.get.quantiles <- function(data1, data2, ranked.simex=FALSE) {
if (is.character(ranked.simex)) {
use.original.ranking.system <- TRUE; ranked.simex <- TRUE
} else use.original.ranking.system <- FALSE
if (ranked.simex) {
for (p in seq.int(3)) { # Additional values between the tau predicted values - 1/8th percentiles for ranking
dataX <- data1[,(seq.int(ncol(data1))-1L)] + t(apply(data1, 1, diff))/2
data1 <- cbind(data1, dataX)[, order(c(seq.int(ncol(data1)), seq.int(ncol(dataX))))]
if (!is.matrix(data1) & is.vector(data1)) { # Account for edge cases where a single student is fed in (e.g., baseline)
data1 <- matrix(data1, nrow=1, byrow=TRUE)
}
}
tmp.zero <- 794L
} else tmp.zero <- 101L
V1 <- NULL
tmp <- as.data.table(max.col(cbind(data1 < data2, FALSE), "last"))[V1==tmp.zero, V1 := 0L]
if (ranked.simex) tmp[, V1 := V1/8]
if (!is.null(sgp.quantiles.labels)) {
setattr(tmp[['V1']] <- as.factor(tmp[['V1']]), "levels", sgp.quantiles.labels)
return(as.integer(levels(tmp[['V1']]))[tmp[['V1']]])
} else {
if (!is.null(sgp.loss.hoss.adjustment)) {
my.path.knots.boundaries <- get.my.knots.boundaries.path(sgp.labels$my.subject, as.character(sgp.labels$my.year))
tmp.hoss <- eval(parse(text=paste0("Knots_Boundaries", my.path.knots.boundaries, "[['loss.hoss_", tmp.last, "']][2L]")))
if (length(tmp.index <- which(data2>=tmp.hoss)) > 0L) {
if (ranked.simex) {
tmp[tmp.index, V1:=as.double(apply(data.table(data1 > data2, TRUE)[tmp.index], 1, function(x) which.max(x)-1L))]
if (!use.original.ranking.system) tmp[tmp.index, V1 := V1/8]
} else tmp[tmp.index, V1:=apply(data.table(data1 > data2, TRUE)[tmp.index], 1, function(x) which.max(x)-1L)]
}
}
if (convert.0and100) {
tmp[V1 %in% c(0L, 100L), V1 := fifelse(V1 == 0L, 1L, 99L)]
}
return(tmp[['V1']])
}
}
.get.percentile.cuts <- function(data1) {
tmp <- round(data1[ , percentile.cuts+1L, drop=FALSE], digits=percuts.digits)
if (convert.using.loss.hoss) {
my.path.knots.boundaries <- get.my.knots.boundaries.path(sgp.labels[['my.subject']], as.character(sgp.labels[['my.year']]))
bnd <- eval(parse(text=paste0("Knots_Boundaries", my.path.knots.boundaries, "[['loss.hoss_", tmp.last, "']]")))
tmp[tmp < bnd[1L]] <- bnd[1L]
tmp[tmp > bnd[2L]] <- bnd[2L]
}
colnames(tmp) <- paste0("PERCENTILE_CUT_", percentile.cuts)
return(tmp)
}
.get.best.cuts <- function(list.of.cuts, label.suffix=NULL) {
cuts.best <- data.table(rbindlist(list.of.cuts), key="ID")
cuts.best <- cuts.best[c(which(!duplicated(cuts.best, by=key(cuts.best)))[-1L]-1L, dim(cuts.best)[1L])][,-1L, with=FALSE]
if (!is.null(label.suffix)) setnames(cuts.best, names(cuts.best), paste(names(cuts.best), label.suffix, sep="_"))
return(cuts.best)
}
split.location <- function(years) sapply(strsplit(years, '_'), length)[1L]
###
### SIMEX function
###
simex.sgp <- function(
state,
csem.data.vnames=NULL,
lambda,
B,
simex.sample.size,
extrapolation,
save.matrices,
simex.use.my.coefficient.matrices=NULL,
calculate.simex.sgps,
dependent.var.error=FALSE,
use.cohort.for.ranking=FALSE,
use.original.ranking.system=FALSE,
set.seed.for.sim.data=TRUE,
verbose=FALSE) {
GRADE <- CONTENT_AREA <- YEAR <- V1 <- Lambda <- tau <- b <- .SD <- TEMP <- CSEM <- VARIABLE <- NULL ## To avoid R CMD check warnings
### simex.sgp internal utility functions
getSIMEXdata <- function(dbase, z, k=NULL, predictions=FALSE) {
if (predictions) {
data.table::fread(file.path(dbase, paste0("simex_data_", z, ".csv")), header=TRUE, showProgress = FALSE,
select = paste(c("ID", paste0('prior_', k:1L), "final_yr")), verbose = FALSE)
} else {
data.table::fread(file.path(dbase, paste0("simex_data_", z, ".csv")), header=TRUE, showProgress = FALSE, verbose = FALSE)
}
} ### END getSIMEXdata function
rq.sgp <- function(...) { # Function needs to be nested within the simex.sgp function to avoid data copying with SNOW
if (rq.method == "br") {
tmp.res <- quantreg::rq(method="br", ...)[['coefficients']]
} else {
tmp.res <- try(quantreg::rq(method=rq.method, ...)[['coefficients']], silent=TRUE)
if (inherits(tmp.res, "try-error")) {
tmp.res <- quantreg::rq(method="br", ...)[['coefficients']]
}
}
return(tmp.res)
} ### END rq.sgp function
rq.mtx <- function(tmp.gp.iter, lam, rqdata) {
mod <- character()
s4Ks <- "Knots=list("
s4Bs <- "Boundaries=list("
for (i in seq_along(tmp.gp.iter)) {
knt <- paste0("Knots_Boundaries", my.path.knots.boundaries, "[['Lambda_", lam, "']][['knots_", tmp.gp.iter[i], "']]")
bnd <- paste0("Knots_Boundaries", my.path.knots.boundaries, "[['Lambda_", lam, "']][['boundaries_", tmp.gp.iter[i], "']]")
mod <- paste0(mod, " + bs(prior_", i, ", knots=", knt, ", Boundary.knots=", bnd, ")")
s4Ks <- paste0(s4Ks, "knots_", tmp.gp.iter[i], "=", knt, ",")
s4Bs <- paste0(s4Bs, "boundaries_", tmp.gp.iter[i], "=", bnd, ",")
}
tmp.mtx <- eval(parse(text=paste0("rq.sgp(final_yr ~", substring(mod,4), ", tau=taus, data = rqdata)")))
tmp.version <- list(
SGP_Package_Version=as.character(packageVersion("SGP")),
Date_Prepared=prettyDate(),
Matrix_Information=list(
N=dim(rqdata)[1L],
Model=paste0("rq.sgp(final_yr ~", substring(mod,4), ", tau=taus, data = rqdata)"),
SGPt=if (is.null(SGPt)) NULL else list(VARIABLES=unlist(SGPt), MAX_TIME=max(rqdata$TIME, na.rm=TRUE), MAX_TIME_PRIOR=max(rqdata$TIME-rqdata$TIME_LAG, na.rm=TRUE), RANGE_TIME_LAG=range(rqdata$TIME_LAG))))
eval(parse(text= paste0("new('splineMatrix', tmp.mtx, ", substring(s4Ks, 1L, nchar(s4Ks)-1L), "), ", substring(s4Bs, 1L, nchar(s4Bs)-1L), "), ",
"Content_Areas=list(as.character(tail(content_area.progression, k+1L))), ",
"Grade_Progression=list(as.character(tail(tmp.slot.gp, k+1L))), ",
"Time=list(as.character(tail(year.progression, k+1L))), ",
"Time_Lags=list(as.numeric(tail(year_lags.progression, k))), ",
"Version=tmp.version)")))
} ### END rq.mtx function
createBigData <- function(tmp.data, perturb.var, L, dependent.var.error) {
# Function that creates big.data object from which SIMEX SGPs are calculated
if (set.seed.for.sim.data) {
set.seed(as.integer(ceiling(ifelse(is.null(sgp.percentiles.set.seed), 369, sgp.percentiles.set.seed)*L)))
}
big.data <- rbindlist(replicate(B, tmp.data, simplify = FALSE))[, b:=rep(seq.int(B), each=n.records)]
if (dependent.var.error) csem.col.offset <- (ncol(big.data)-2)/2 else csem.col.offset <- (ncol(big.data)-1)/2
for (perturb.var.iter in rev(seq_along(perturb.var))) {
setnames(big.data, c(1L+perturb.var.iter, 1L+perturb.var.iter+csem.col.offset), c("VARIABLE", "CSEM"))
unique.key <- c("VARIABLE", names(big.data)[1L+csem.col.offset], "b", "CSEM")
setkeyv(big.data, unique.key)
big.data[,(1L+perturb.var.iter) := unique(big.data, by=unique.key)[,"TEMP" := VARIABLE+sqrt(L)*CSEM*rnorm(.N)][big.data[,unique.key, with=FALSE], on=unique.key][["TEMP"]]]
setnames(big.data, c("VARIABLE", "CSEM"), paste0(c("VARIABLE", "DONE_CSEM"), perturb.var.iter))
}
big.data[,grep("DONE", names(big.data), value=TRUE):=NULL]
setnames(big.data, c("ID", paste0("prior_", (csem.col.offset-1L):1L), "final_yr", "b"))
setkey(big.data, b, ID)
return(big.data)
} ### END createBigData function
get.simex.ranking.info <- function(table_list, cap, gp, yp, ylp) {
table.index <-
which(sapply(table_list,
function(f) {
identical(attr(f, "content_area_progression"), cap) &
identical(attr(f, "grade_progression"), gp) &
identical(attr(f, "year_progression"), yp) &
identical(attr(f, "year_lags_progression"), ylp)
}))
if (!length(table.index)) {
stop("\n\t\tNo matching SIMEX `ranked_simex_table` entries found for progression ",
paste(gsub(" EOCT", "", paste(cap, gp)), collapse = " --> "))
}
if (length(table.index) > 1L){
g <- tail(gp, 1)
ca <- tail(cap, 1)
pr <- head(gsub(" EOCT", "", paste(cap, gp)), -1) # needs separate pastes? `paste(pr, collapse = ", ")` -v- SMH...
msg.prior.info <- paste0(" { Prior", ifelse(length(pr) == 1L, ": ", "s: "), paste(pr, collapse = ", "), " }")
messageSGP(
c("\n\t\tMultiple matching SIMEX `ranked_simex_table` entries for", ca, if(g != "EOCT"){paste(" Grade", g)}, msg.prior.info,
"\n\t\tThe first `ranked_simex_table` entry will be used, but tables with duplicate `attributes` should be investigated!!!",
ifelse(identical(table_list[[table.index[1]]], table_list[[table.index[2]]]),
"\n\t\tThe first SET of duplicate tables are identical, so ... that's encouraging ...\n",
"\n\t\tThe first SET of duplicate tables are NOT identical\n\t\t\t\t!!! INVESTIGATE DIFFERENCES!!!\n"
)))
# sapply(table_list, function(f) {
# paste(attr(f, "content_area_progression"), attr(f, "grade_progression"),
# attr(f, "year_progression"), attr(f, "year_lags_progression"), collapse = ", ")})
}
return(table_list[[table.index[1]]])
}
### Check arguments/define variables
if (is.null(dependent.var.error)) dependent.var.error <- FALSE
if (is.null(use.cohort.for.ranking)) use.cohort.for.ranking <- FALSE
if (is.null(use.original.ranking.system)) use.original.ranking.system <- FALSE
if (is.null(set.seed.for.sim.data)) set.seed.for.sim.data <- TRUE
if (is.null(verbose)) verbose <- FALSE
if (verbose) messageSGP(c("\n\tStarted SIMEX SGP calculation ", rev(content_area.progression)[1L], " Grade ", rev(tmp.gp)[1L], " ", prettyDate()))
if (is.logical(simex.use.my.coefficient.matrices) && !simex.use.my.coefficient.matrices) simex.use.my.coefficient.matrices <- NULL
if (!is.null(state) && !is.null(csem.data.vnames)) stop("SIMEX config can not use both 'state' and 'csem.data.vnames' elements.")
if (!is.null(parallel.config)) {
if (is.null(parallel.config[["WORKERS"]][["SIMEX"]])) tmp.par.config <- NULL else tmp.par.config <- parallel.config
} else tmp.par.config <- NULL
fitted <- extrap <- tmp.quantiles.simex <- simex.coef.matrices <- list()
my.path.knots.boundaries <- get.my.knots.boundaries.path(sgp.labels$my.subject, as.character(sgp.labels$my.year))
if (!is.null(csem.data.vnames)) {
if (length(content_area.progression)==length(csem.data.vnames)) csem.data.vnames <- head(csem.data.vnames, -1L)
if (length(content_area.progression) < length(csem.data.vnames)) csem.data.vnames <- tail(head(csem.data.vnames, -1L), (length(csem.data.vnames)-(length(csem.data.vnames)-length(content_area.progression)+1L))) # grep(paste(head(content_area.progression, -1L), collapse="|"), csem.data.vnames, value=TRUE)
}
if (!is.null(use.my.coefficient.matrices)) { # Passed implicitly from studentGrowthPercentiles arguments
if (exact.grade.progression.sequence) {
simex.matrix.priors <- num.prior
} else {
simex.matrix.priors <- seq(num.prior)
}
} else simex.matrix.priors <- coefficient.matrix.priors
### Loop over priors
for (k in simex.matrix.priors) {
tmp.data <- .get.panel.data(ss.data, k, by.grade, tmp.gp)
n.records <- nrow(tmp.data)
tmp.num.variables <- dim(tmp.data)[2L]
tmp.gp.iter <- rev(tmp.gp)[2L:(k+1L)]
if (dependent.var.error) {
perturb.var <- rev(tmp.gp)[seq.int((k+1L))]
start.index <- 1L
num.perturb.vars <- tmp.num.variables+1L
} else {
perturb.var <- tmp.gp.iter
start.index <- 2L
num.perturb.vars <- tmp.num.variables
}
tmp.ca.iter <- rev(content_area.progression)[start.index:(k+1L)]
tmp.yr.iter <- rev(year.progression)[start.index:(k+1L)]
## naive model
# if (calculate.simex.sgps) { # Always calculate SIMEX SGPs (for ranked SIMEX table)
fitted[[paste0("order_", k)]] <- matrix(0, nrow=length(lambda), ncol=n.records*length(taus))
tmp.matrix <- getsplineMatrices(
Coefficient_Matrices[[tmp.path.coefficient.matrices]],
tail(content_area.progression, k+1L),
tail(grade.progression, k+1L),
tail(year.progression, k+1L),
tail(year_lags.progression, k),
my.matrix.order=k,
my.matrix.time.dependency=SGPt)[[1L]]
fitted[[paste0("order_", k)]][1L,] <- c(.get.percentile.predictions(tmp.data, tmp.matrix))
# }
# add csems to tmp.data
if (!is.null(state)) {
for (g in rev(seq_along(perturb.var))) {
if ("YEAR" %in% names(SGP::SGPstateData[[state]][["Assessment_Program_Information"]][["CSEM"]])) {
CSEM_Data <- SGP::SGPstateData[[state]][["Assessment_Program_Information"]][["CSEM"]][
GRADE==perturb.var[g] & CONTENT_AREA==tmp.ca.iter[g] & YEAR==tmp.yr.iter[g]]
} else {
CSEM_Data <- SGP::SGPstateData[[state]][["Assessment_Program_Information"]][["CSEM"]][
GRADE==perturb.var[g] & CONTENT_AREA==tmp.ca.iter[g]]
}
if (dim(CSEM_Data)[1L] == 0L) stop(paste('CSEM data for', tmp.ca.iter[g], 'Grade', perturb.var[g], 'is required to use SIMEX functionality, but is not available in SGPstateData. Please contact package administrators to add CSEM data.'))
CSEM_Function <- splinefun(CSEM_Data[["SCALE_SCORE"]], CSEM_Data[["SCALE_SCORE_CSEM"]], method="natural")
tmp.data[, paste0("icsem", perturb.var[g], tmp.ca.iter[g], tmp.yr.iter[g]) := CSEM_Function(tmp.data[[num.perturb.vars-g]])]
}
}
if (!is.null(csem.data.vnames)) {
for (g in rev(seq_along(perturb.var))) {
tmp.data[, paste0("icsem", perturb.var[g], tmp.ca.iter[g], tmp.yr.iter[g]) := Panel_Data[list(tmp.data$ID)][[rev(csem.data.vnames)[g]]]]
}
}
if (verbose) messageSGP(c("\t\t", rev(content_area.progression)[1L], " Grade ", rev(tmp.gp)[1L], " Order ", k, " Started simulation process ", prettyDate()))
for (L in lambda[-1L]) {
big.data <- createBigData(tmp.data, perturb.var, L, dependent.var.error)
if (is.null(simex.use.my.coefficient.matrices) & !identical(sgp.labels[['my.extra.label']], "BASELINE")) {
ifelse(dependent.var.error, knots_boundaries.iter <- tail(perturb.var, -1), knots_boundaries.iter <- perturb.var)
for (g in seq_along(knots_boundaries.iter)) {
ks <- big.data[, as.list(as.vector(unlist(round(quantile(big.data[[g+1L]], probs=knot.cut.percentiles, na.rm=TRUE), digits=3L))))] # Knots
bs <- big.data[, as.list(as.vector(round(extendrange(big.data[[g+1L]], f=0.1), digits=3L)))] # Boundaries
lh <- big.data[, as.list(as.vector(round(extendrange(big.data[[g+1L]], f=0.0), digits=3L)))] # LOSS/HOSS
eval(parse(text=paste0("Knots_Boundaries", my.path.knots.boundaries, "[['Lambda_", L, "']][['knots_", rev(knots_boundaries.iter)[g],
"']] <- c(ks[,V1], ks[,V2], ks[,V3], ks[,V4])")))
eval(parse(text=paste0("Knots_Boundaries", my.path.knots.boundaries, "[['Lambda_", L, "']][['boundaries_", rev(knots_boundaries.iter)[g],
"']] <- c(bs[,V1], bs[,V2])")))
eval(parse(text=paste0("Knots_Boundaries", my.path.knots.boundaries, "[['Lambda_", L, "']][['loss.hoss_", rev(knots_boundaries.iter)[g],
"']] <- c(lh[,V1], lh[,V2])")))
}
}
## Establish the simulation iterations - either 1) 1:B, or 2) a sample of either B or the number of previously computed matrices
sim.iters <- seq.int(B)
if (!is.null(tmp.par.config)) { # Not Sequential
## Write big.data to disk and remove from memory
if (!exists('year.progression.for.norm.group')) year.progression.for.norm.group <- year.progression # Needed during Baseline Matrix construction
tmp.dbname <- tempdir()
sapply(sim.iters, function(z) data.table::fwrite(big.data[list(z)], file=file.path(tmp.dbname, paste0("simex_data_", z, ".csv")), showProgress = FALSE, verbose = FALSE))
}
if (!is.null(simex.use.my.coefficient.matrices)) { # Element from the 'calculate.simex' argument list.
available.matrices <- unlist(getsplineMatrices(
Coefficient_Matrices[[paste0(tmp.path.coefficient.matrices, '.SIMEX')]][[
paste("qrmatrices", tail(tmp.gp,1L), k, sep="_")]][[paste0("lambda_", L)]],
tail(content_area.progression, k+1L),
tail(grade.progression, k+1L),
tail(year.progression, k+1L),
tail(year_lags.progression, k),
my.exact.grade.progression.sequence=TRUE,
return.multiple.matrices=TRUE,
my.matrix.order=k,
my.matrix.time.dependency=SGPt), recursive=FALSE)
if (length(available.matrices) > B) sim.iters <- sample.int(length(available.matrices), B) # Stays as 1:B when length(available.matrices) == B
if (length(available.matrices) < B) sim.iters <- sample.int(length(available.matrices), B, replace=TRUE)
}
if (is.null(tmp.par.config)) { # Sequential
if (verbose) messageSGP(c("\t\t\tStarted coefficient matrix calculation, Lambda ", L, ": ", prettyDate()))
if (is.null(simex.use.my.coefficient.matrices)) {
if (!is.null(simex.sample.size) && n.records > simex.sample.size) {
foreach::registerDoSEQ()
tmp.random <- foreach(z=iter(sim.iters)) %dorng% sample(seq.int(n.records), simex.sample.size)
}
for (z in seq_along(sim.iters)) {
if (is.null(simex.sample.size) || n.records <= simex.sample.size) {
simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]][[z]] <-
rq.mtx(tmp.gp.iter[seq.int(k)], lam=L, rqdata=big.data[list(z)][, b:=NULL])
} else {
simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]][[z]] <-
rq.mtx(tmp.gp.iter[seq.int(k)], lam=L, rqdata=big.data[list(z)][, b:=NULL][tmp.random[[z]]])
}
}
} else simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]] <- available.matrices[sim.iters]
# if (calculate.simex.sgps) { # Always calculate SIMEX SGPs (for ranked SIMEX table)
if (verbose) messageSGP(c("\t\t\tStarted percentile prediction calculation, Lambda ", L, ": ", prettyDate()))
for (z in seq_along(sim.iters)) {
fitted[[paste0("order_", k)]][which(lambda==L),] <- fitted[[paste0("order_", k)]][which(lambda==L),] +
c(.get.percentile.predictions(big.data[list(z)][, paste(c("ID", paste0('prior_', k:1L), "final_yr")), with=FALSE],
simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]][[z]])/B)
}
# }
} else {### Parallel over sim.iters
### Always use FOREACH for coefficient matrix production -- need %dorng% to guarantee reproducibility across plateforms (also MUCH more efficient with SNOW/Windows).
if (toupper(tmp.par.config[["BACKEND"]]) != "FOREACH") tmp.par.config[["BACKEND"]] <- "FOREACH"; tmp.par.config[["TYPE"]] <- "doParallel"
par.start <- startParallel(tmp.par.config, 'SIMEX')
## Note that if you use the parallel.config for SIMEX here, you can also use it for TAUS in the naive analysis
## Example parallel.config argument: '... parallel.config=list(BACKEND="FOREACH", TYPE="doParallel", WORKERS=list(SIMEX = 4, TAUS = 4))'
## Calculate coefficient matricies (if needed/requested)
if (is.null(simex.use.my.coefficient.matrices)) {
if (verbose) messageSGP(c("\t\t\tStarted coefficient matrix calculation, Lambda ", L, ": ", prettyDate()))
if (is.null(simex.sample.size) || n.records <= simex.sample.size) {
simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]] <-
# foreach(z=iter(sim.iters), .packages=c("quantreg", "data.table"),
foreach(z=iter(sim.iters),
.export=c("Knots_Boundaries", "rq.method", "taus", "content_area.progression", "tmp.slot.gp", "year.progression", "year_lags.progression", "SGPt", "rq.sgp", "get.my.knots.boundaries.path"),
.options.mpi=par.start$foreach.options, .options.multicore=par.start$foreach.options, .options.snow=par.start$foreach.options) %dopar% {
rq.mtx(tmp.gp.iter[seq.int(k)], lam=L, rqdata=getSIMEXdata(tmp.dbname, z))
}
} else {
simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]] <-
foreach(z=iter(sim.iters), .packages=c("quantreg", "data.table"),
.export=c("Knots_Boundaries", "rq.method", "taus", "content_area.progression", "tmp.slot.gp", "year.progression", "year_lags.progression", "SGPt", "rq.sgp", "get.my.knots.boundaries.path"),
.options.mpi=par.start$foreach.options, .options.multicore=par.start$foreach.options, .options.snow=par.start$foreach.options) %dorng% {
rq.mtx(tmp.gp.iter[seq.int(k)], lam=L, rqdata=getSIMEXdata(tmp.dbname, z)[sample(seq.int(n.records), simex.sample.size)])
}
}
} else {
simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]] <- available.matrices[sim.iters]
### Re-set the random seed to match when coef matrices are produced. Otherwise seed is off when data is simulated in subsequent L loops.
if (is.null(simex.sample.size)) {
### Use the N from the matrices rather than `simex.sample.size` - since that element may not be specified in the `calculate.simex` argument/list.
simex.mtx.size <- unique(sapply(sim.iters, function(f) available.matrices[[f]]@Version[["Matrix_Information"]][["N"]]))
if (all(n.records > simex.mtx.size)) tmp.random.reset <- foreach(z=iter(sim.iters)) %dorng% sample(seq.int(n.records), simex.mtx.size)
}
}
if (!all(sapply(simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]], is.splineMatrix))) {
recalc.index <- which(!sapply(simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]], is.splineMatrix))
messageSGP(c("\n\t\t", rev(content_area.progression)[1L], " Grade ", rev(tmp.gp)[1L], " Order ", k, " Coefficient Matrix process(es) ", recalc.index, "FAILED! Attempting to recalculate sequentially..."))
for (z in recalc.index) {
if (is.null(simex.sample.size) || n.records <= simex.sample.size) {
simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]][[z]] <-
rq.mtx(tmp.gp.iter[seq.int(k)], lam=L, rqdata=as.data.table(getSIMEXdata(tmp.dbname, z)))
} else {
simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]][[z]] <-
rq.mtx(tmp.gp.iter[seq.int(k)], lam=L, rqdata=as.data.table(getSIMEXdata(tmp.dbname, z))[sample(seq.int(n.records), simex.sample.size),])
}
}
}
## get percentile predictions from coefficient matricies
# if (calculate.simex.sgps) {
if (verbose) messageSGP(c("\t\t\tStarted percentile prediction calculation, Lambda ", L, ": ", prettyDate()))
mtx.subset <- simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste0("lambda_", L)]] # Save on memory copying to R SNOW workers
environment(.get.percentile.predictions) <- environment(.smooth.bound.iso.row) <- environment()
fitted[[paste0("order_", k)]][which(lambda==L),] <-
foreach(z=iter(seq_along(sim.iters)), .combine="+", .export=c('tmp.gp', 'taus', 'sgp.loss.hoss.adjustment', 'isotonize', 'SGPt', 'get.my.knots.boundaries.path'),
.options.multicore=par.start$foreach.options) %dopar% { # .options.snow=par.start$foreach.options
c(.get.percentile.predictions(my.matrix=mtx.subset[[z]], my.data=getSIMEXdata(tmp.dbname, z, k, predictions=TRUE))/B)
}
# }
stopParallel(tmp.par.config, par.start)
} ### END Parallel over sim.iters
if (!is.null(tmp.par.config)) unlink(tmp.dbname)
} ### END for (L in lambda[-1L])
if (verbose) messageSGP(c("\t\t", rev(content_area.progression)[1L], " Grade ", rev(tmp.gp)[1L], " Order ", k, " Simulation process complete ", prettyDate()))
# if (calculate.simex.sgps) { # Always calculate SIMEX SGPs (for ranked SIMEX table)
switch(extrapolation,
LINEAR = fit <- lm(fitted[[paste0("order_", k)]] ~ lambda),
QUADRATIC = fit <- lm(fitted[[paste0("order_", k)]] ~ lambda + I(lambda^2)))
extrap[[paste0("order_", k)]] <-
matrix(.smooth.bound.iso.row(data.table(ID=seq.int(n.records), X=predict(fit, newdata=data.frame(lambda=-1L))[1L,]), isotonize, sgp.loss.hoss.adjustment),
ncol=length(taus), byrow=TRUE)
if (is.null(simex.use.my.coefficient.matrices)) {
ranked.simex.quantile.values <- .get.quantiles(extrap[[paste0("order_", k)]], tmp.data[[tmp.num.variables]], ranked.simex=ifelse(use.original.ranking.system, "use.original.ranking.system", TRUE))
# simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste("ranked_simex_table", tail(tmp.gp, 1L), k, sep="_")]] <- table(ranked.simex.quantile.values)
# simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][[paste("n_records", tail(tmp.gp, 1L), k, sep="_")]] <- n.records
ranked_simex_table <- table(ranked.simex.quantile.values)
attr(ranked_simex_table, 'content_area_progression') <- tail(content_area.progression, k+1L)
attr(ranked_simex_table, 'grade_progression') <- tail(grade.progression, k+1L)
attr(ranked_simex_table, 'year_progression') <- tail(year.progression, k+1L)
attr(ranked_simex_table, 'year_lags_progression') <- tail(year_lags.progression, k)
attr(ranked_simex_table, 'n_records') <- n.records
simex.coef.matrices[[paste("qrmatrices", tail(tmp.gp, 1L), k, sep="_")]][["ranked_simex_table"]][[1]] <- ranked_simex_table
tmp.quantiles.simex[[k]] <- data.table(ID=tmp.data[["ID"]], SIMEX_ORDER=k,
SGP_SIMEX=.get.quantiles(extrap[[paste0("order_", k)]], tmp.data[[tmp.num.variables]]),
SGP_SIMEX_RANKED=as.integer(round(100*(data.table::frank(ties.method = "average", x = ranked.simex.quantile.values)/n.records), 0)))
} else {
if (any(grepl("ranked_simex_table", names(Coefficient_Matrices[[paste0(tmp.path.coefficient.matrices, '.SIMEX')]][[paste("qrmatrices", tail(tmp.gp,1L), k, sep="_")]])))) {
# if (length(Coefficient_Matrices[[paste0(tmp.path.coefficient.matrices, '.SIMEX')]][[paste("qrmatrices", tail(tmp.gp,1L), k, sep="_")]]) > (length(lambda)-1)) {
# ranked.simex.info <- Coefficient_Matrices[[paste0(tmp.path.coefficient.matrices, '.SIMEX')]][[paste("qrmatrices", tail(tmp.gp,1L), k, sep="_")]][length(lambda):(length(lambda)+1)]
ranked.simex.info <- get.simex.ranking.info(
Coefficient_Matrices[[paste0(tmp.path.coefficient.matrices, '.SIMEX')]][[paste("qrmatrices", tail(tmp.gp,1L), k, sep="_")]][["ranked_simex_table"]],
tail(content_area.progression, k+1L), tail(grade.progression, k+1L), tail(year.progression, k+1L), tail(year_lags.progression, k))
ranked.simex.tf <- TRUE
} else {
if (use.cohort.for.ranking) {
ranked.simex.tf <- TRUE
} else {
messageSGP("\tRanked SIMEX SGP calculation with pre-calculated SGPs is only available with info embedded as of SGP version 1.9-4.0\n\tor setting parameter use.cohort.for.ranking = TRUE in the calculate.simex configuration.\n\tNAs will be returned for SGP_SIMEX_RANKED.")
ranked.simex.tf <- FALSE
}
}
if (ranked.simex.tf) {
tmp.quantiles.simex[[k]] <-
data.table(
ID = tmp.data[["ID"]],
SIMEX_ORDER = k,
SGP_SIMEX =
.get.quantiles(extrap[[paste0("order_", k)]], tmp.data[[tmp.num.variables]])
)
if (use.cohort.for.ranking) {
# Use `use.cohort.for.ranking=TRUE` if reproducing values with original data OR to rank against the updated/new cohort data ONLY
tmp.quantiles.simex[[k]][,
SGP_SIMEX_RANKED :=
as.integer(round(100*(
data.table::frank(
ties.method = "average",
x = .get.quantiles(
extrap[[paste0("order_", k)]],
tmp.data[[tmp.num.variables]],
ranked.simex =
ifelse(use.original.ranking.system, "use.original.ranking.system", TRUE)
))/n.records
), 0))
]
} else {
# creates a new "average" rank of the original data and the updated/new cohort
tmp.quantiles.simex[[k]][,
SGP_SIMEX_RANKED :=
head(as.integer(round(100*(
data.table::frank(
ties.method = "average",
x = c(.get.quantiles(
extrap[[paste0("order_", k)]],
tmp.data[[tmp.num.variables]],
ranked.simex =
ifelse(use.original.ranking.system, "use.original.ranking.system", TRUE)
),
as.numeric(rep(names(ranked.simex.info), ranked.simex.info))))/(n.records+attr(ranked.simex.info, "n_records"))
), 0)), n.records)
]
}
}
}
}### END for (k in simex.matrix.priors)
if (verbose) messageSGP(c("\tFinished SIMEX SGP calculation ", rev(content_area.progression)[1L], " Grade ", rev(tmp.gp)[1L], " ", prettyDate()))
if (is.null(save.matrices)) simex.coef.matrices <- NULL
if (calculate.simex.sgps) {
quantile.data.simex <- data.table(rbindlist(tmp.quantiles.simex), key=c("ID", "SIMEX_ORDER"))
# invisible(quantile.data.simex[, SGP_SIMEX_RANKED := as.integer(round(100*(rank(SGP_SIMEX, ties.method = "average")/length(SGP_SIMEX)), 0)), by = "SIMEX_ORDER"])
if (convert.0and100) {
quantile.data.simex[SGP_SIMEX_RANKED %in% c(0L, 100L), SGP_SIMEX_RANKED := fifelse(SGP_SIMEX_RANKED == 0L, 1L, 99L)]
}
setkey(quantile.data.simex, ID) # first key on ID and SIMEX_ORDER, then re-key on ID only to insure sorted order. Don't rely on rbindlist/k ordering...
} else { # set up empty data.table for ddcast and subsets below.
quantile.data.simex <-
data.table("ID"=NA, "SIMEX_ORDER"=NA, "SGP_SIMEX"=NA, "SGP_SIMEX_RANKED"=NA)
}
if (print.other.gp) {
tmp.quantile.data.simex <- ddcast(quantile.data.simex, ID ~ SIMEX_ORDER, value.var=setdiff(names(quantile.data.simex), c("ID", "SIMEX_ORDER")), sep="_ORDER_")
quantile.data.simex <- data.table(tmp.quantile.data.simex,
SGP_SIMEX=quantile.data.simex[c(which(!duplicated(quantile.data.simex, by=key(quantile.data.simex)))[-1L]-1L, dim(quantile.data.simex)[1L])][["SGP_SIMEX"]],
SGP_SIMEX_RANKED=quantile.data.simex[c(which(!duplicated(quantile.data.simex, by=key(quantile.data.simex)))[-1L]-1L, dim(quantile.data.simex)[1L])][["SGP_SIMEX_RANKED"]])
return(list(
DT=quantile.data.simex,
MATRICES=simex.coef.matrices))
} else {
if (print.sgp.order | return.norm.group.identifier) {
return(list(
DT=quantile.data.simex[c(which(!duplicated(quantile.data.simex, by=key(quantile.data.simex)))[-1L]-1L, dim(quantile.data.simex)[1L])],
MATRICES=simex.coef.matrices))
} else {
return(list(
DT=quantile.data.simex[c(which(!duplicated(quantile.data.simex, by=key(quantile.data.simex)))[-1L]-1L, dim(quantile.data.simex)[1L]), c("ID", "SGP_SIMEX", "SGP_SIMEX_RANKED"), with=FALSE],
MATRICES=simex.coef.matrices))
}
}
if (verbose) messageSGP(c("\tFinished SIMEX SGP calculation ", rev(content_area.progression)[1L], " Grade ", rev(tmp.gp)[1L], " ", prettyDate(), "\n"))
} ### END simex.sgp function
############################################################################
###
### Data Preparation & Checks
###
############################################################################
ID <- tmp.messages <- ORDER <- SCALE_SCORE_PRIOR <- SGP <- PREFERENCE <- NULL
if (missing(panel.data)) {
stop("User must supply student achievement data for student growth percentile calculations. NOTE: data is now supplied to function using panel.data argument. See help page for details.")
}
if (!(is.matrix(panel.data) || is.list(panel.data))) {
stop("Supplied panel.data not of a supported class. See help for details of supported classes")
}
if (inherits(panel.data, "list") && !"Panel_Data" %in% names(panel.data)) {
stop("Supplied panel.data missing Panel_Data")
}
if (inherits(panel.data, "list") && !is.data.frame(panel.data[["Panel_Data"]])) {
stop("Supplied panel.data$Panel_Data is not a data.frame or a data.table")
}
if (inherits(panel.data, "list") && !is.null(panel.data[['Coefficient_Matrices']])) {
panel.data[['Coefficient_Matrices']] <- checksplineMatrix(panel.data[['Coefficient_Matrices']])
}
if (!missing(sgp.labels) && !is.list(sgp.labels)) {
stop("Please specify an appropriate list of SGP function labels (sgp.labels). See help page for details.")
}
if (!identical(names(sgp.labels), c("my.year", "my.subject")) &&
!identical(names(sgp.labels), c("my.year", "my.subject", "my.extra.label"))) {
stop("Please specify an appropriate list for sgp.labels. See help page for details.")
}
sgp.labels <- lapply(sgp.labels, toupper)
tmp.path <- .create.path(sgp.labels)
if (!missing(growth.levels)) {
tmp.growth.levels <- list()
if (!is.list(growth.levels) && !is.character(growth.levels)) {
tmp.messages <- c(tmp.messages, "\t\tNOTE: `growth.levels` must be supplied as a list or character abbreviation. See help page for details.\n\t\t\t`studentGrowthPercentiles` will be calculated without augmented growth levels.\n")
tf.growth.levels <- FALSE
}
if (is.list(growth.levels)) {
if (!identical(names(growth.levels), c("my.cuts", "my.levels"))) {
tmp.messages <- c(tmp.messages, "\t\tNOTE: Please specify an appropriate list for `growth.levels`. See help page for details.\n\t\t\tStudent growth percentiles will be calculated without augmented growth levels.\n")
tf.growth.levels <- FALSE
} else {
tmp.growth.levels <- growth.levels
tf.growth.levels <- TRUE
}
}
if (is.character(growth.levels)) {
if (is.null(SGP::SGPstateData[[growth.levels]][["Growth"]][["Levels"]])) {
tmp.messages <- c(tmp.messages, "\t\tNOTE: Growth Levels are currently not specified for the indicated state.\n\t\t\tPlease contact the SGP package administrator to have your state's data included in the package.\n\t\t\tStudent growth percentiles will be calculated without augmented growth levels.\n")
tf.growth.levels <- FALSE
} else {
tmp.growth.levels[["my.cuts"]] <- SGP::SGPstateData[[growth.levels]][["Growth"]][["Cutscores"]][["Cuts"]]
tmp.growth.levels[["my.levels"]] <- SGP::SGPstateData[[growth.levels]][["Growth"]][["Levels"]]
tf.growth.levels <- TRUE
}
}
} else {
tf.growth.levels <- FALSE
}
if (!missing(use.my.knots.boundaries)) {
if (!is.list(use.my.knots.boundaries) && !is.character(use.my.knots.boundaries)) {
stop("use.my.knots.boundaries must be supplied as a list or character abbreviation. See help page for details.")
}
if (is.list(use.my.knots.boundaries)) {
if (!inherits(panel.data, "list")) {
stop("use.my.knots.boundaries is only appropriate when panel data is of class list. See help page for details.")
}
if (!identical(names(use.my.knots.boundaries), c("my.year", "my.subject")) &
!identical(names(use.my.knots.boundaries), c("my.year", "my.subject", "my.extra.label"))) {
stop("Please specify an appropriate list for use.my.knots.boundaries. See help page for details.")
}
tmp.path.knots.boundaries <- .create.path(use.my.knots.boundaries, pieces=c("my.subject", "my.year"))
if (is.null(panel.data[["Knots_Boundaries"]]) | is.null(panel.data[["Knots_Boundaries"]][[tmp.path.knots.boundaries]])) {
stop("Knots and Boundaries indicated by use.my.knots.boundaries are not included.")
}
}
if (is.character(use.my.knots.boundaries)) {
if (is.null(SGP::SGPstateData[[use.my.knots.boundaries]][["Achievement"]][["Knots_Boundaries"]])) {
tmp.messages <- c(tmp.messages, paste0("\t\tNOTE: Knots and Boundaries are currently not implemented for the state indicated (",
use.my.knots.boundaries, "). Knots and boundaries will be calculated from the data.", "
Please contact the SGP package administrator to have your Knots and Boundaries included in the package\n"))
}
tmp.path.knots.boundaries <- .create.path(sgp.labels, pieces=c("my.subject", "my.year"))
}
} else {
tmp.path.knots.boundaries <- .create.path(sgp.labels, pieces=c("my.subject", "my.year"))
}
if (!is.null(use.my.coefficient.matrices) && !identical(use.my.coefficient.matrices, TRUE)) {
if (!inherits(panel.data, "list")) {
stop("use.my.coefficient.matrices is only appropriate when panel data is of class list. See help page for details.")
}
if (!is.list(use.my.coefficient.matrices)) {
stop("Please specify an appropriate list for argument 'use.my.coefficient.matrices'. See help page for details.")
}
if (!identical(names(use.my.coefficient.matrices), c("my.year", "my.subject")) &&
!identical(names(use.my.coefficient.matrices), c("my.year", "my.subject", "my.extra.label"))) {
stop("Please specify an appropriate list for argument 'use.my.coefficient.matrices'. See help page for details.")
}
tmp.path.coefficient.matrices <- .create.path(use.my.coefficient.matrices, pieces=c("my.subject", "my.year"))
if (is.null(panel.data[["Coefficient_Matrices"]]) || is.null(panel.data[["Coefficient_Matrices"]][[tmp.path.coefficient.matrices]])) {
stop("Coefficient matrices indicated by argument 'use.my.coefficient.matrices' are not included.")
}
} else {
tmp.path.coefficient.matrices <- tmp.path
}
if (is.character(sgp.quantiles)) {
sgp.quantiles <- toupper(sgp.quantiles)
if (sgp.quantiles != "PERCENTILES") {
stop("Character options for sgp.quantiles include only Percentiles at this time. Other options available by specifying a numeric quantity. See help page for details.")
}
taus <- .create_taus(sgp.quantiles)
sgp.quantiles.labels <- NULL
}
if (is.numeric(sgp.quantiles)) {
if (!(all(sgp.quantiles > 0 && sgp.quantiles < 1))) {
stop("Specify sgp.quantiles as as a vector of probabilities between 0 and 1.")
}
taus <- .create_taus(sgp.quantiles)
if (!is.null(sgp.quantiles.labels)) {
if (length(sgp.quantiles.labels)!=length(sgp.quantiles)+1L) stop("Supplied 'sgp.quantiles.labels' must be 1 longer than supplied 'sgp.quantiles'.")
if (any(is.na(as.integer(sgp.quantiles.labels)))) stop("Supplied 'sgp.quantiles.labels' must be integer values.")
sgp.quantiles.labels <- as.integer(sgp.quantiles.labels)
} else {
sgp.quantiles.labels <- as.integer(c(100*taus, 100))
}
}
if (!is.null(percentile.cuts)) {
if (sgp.quantiles != "PERCENTILES") {
stop("percentile.cuts only appropriate for growth percentiles. Set sgp.quantiles to Percentiles to produce requested percentile.cuts.")
}
if (!all(percentile.cuts %in% 0:100)) {
stop("Specified percentile.cuts must be integers between 0 and 100.")
}}
if (!calculate.sgps && (is.character(goodness.of.fit) || goodness.of.fit==TRUE)) {
tmp.messages <- c(tmp.messages, "\t\tNOTE: Goodness-of-Fit tables only produced when calculating SGPs.\n")
}
if (!is.null(calculate.confidence.intervals)) {
csem.tf <- TRUE
if (!is.character(calculate.confidence.intervals) && !is.list(calculate.confidence.intervals)) {
tmp.messages <- c(tmp.messages, "\t\tNOTE: Please supply an appropriate state acronym, variable or list containing details to calculate.confidence.intervals. See help page for details. SGPs will be calculated without confidence intervals.\n")
csem.tf <- FALSE
}
if (is.list(calculate.confidence.intervals)) {
if (!(("state" %in% names(calculate.confidence.intervals)) || ("variable" %in% names(calculate.confidence.intervals)))) {
tmp.messages <- c(tmp.messages, "\t\tNOTE: Please specify an appropriate list for calculate.confidence.intervals including state/csem variable, confidence.quantiles, simulation.iterations, distribution and round. See help page for details. SGPs will be calculated without confidence intervals.\n")
csem.tf <- FALSE
}
if ("variable" %in% names(calculate.confidence.intervals) && is.null(panel.data.vnames)) {
tmp.messages <- c(tmp.messages, "\t\tNOTE: To utilize a supplied CSEM variable for confidence interval calculations you must specify the variables to be used for student growth percentile calculations with the panel.data.vnames argument. SGPs will be calculated without confidence intervals. See help page for details.\n")
csem.tf <- FALSE
}
}
if (is.character(calculate.confidence.intervals)) {
if (!calculate.confidence.intervals %in% c(objects(SGP::SGPstateData), names(panel.data[['Panel_Data']]))) {
tmp.messages <- c(tmp.messages, "\t\tNOTE: Please provide an appropriate state acronym or variable name in supplied data corresponding to CSEMs. See help page for details. SGPs will be calculated without confidence intervals.\n")
csem.tf <- FALSE
}
if (calculate.confidence.intervals %in% objects(SGP::SGPstateData)) {
if ("YEAR" %in% names(SGP::SGPstateData[[calculate.confidence.intervals]][["Assessment_Program_Information"]][["CSEM"]])) {
if (!sgp.labels$my.year %in% unique(SGP::SGPstateData[[calculate.confidence.intervals]][["Assessment_Program_Information"]][["CSEM"]][["YEAR"]])) {
tmp.messages <- c(tmp.messages, "\t\tNOTE: SGPstateData contains year specific CSEMs but year requested is not available. Simulated SGPs and confidence intervals will not be calculated.\n")
csem.tf <- FALSE
}
}
if (dim(SGP::SGPstateData[[calculate.confidence.intervals]][["Assessment_Program_Information"]][["CSEM"]][CONTENT_AREA==sgp.labels$my.subject & GRADE==rev(grade.progression)[1]])[1]==0) {
tmp.messages <- c(tmp.messages, paste0("\t\tNOTE: SGPstateData does not contain content area CSEMs for requested content area '", sgp.labels$my.subject, "'. Simulated SGPs and confidence intervals will not be calculated.\n"))
csem.tf <- FALSE
}
calculate.confidence.intervals <- list(state=calculate.confidence.intervals)
}
if (calculate.confidence.intervals %in% names(panel.data[['Panel_Data']])) {
calculate.confidence.intervals <- list(variable=calculate.confidence.intervals)
}
}
if (is.list(calculate.confidence.intervals) &&
"variable" %in% names(calculate.confidence.intervals) &&
calculate.confidence.intervals$variable %in% names(panel.data[['Panel_Data']]) &&
all(is.na(panel.data[['Panel_Data']][[calculate.confidence.intervals$variable]]))) {
tmp.messages <- c(tmp.messages, paste0("\t\tNOTE: CSEM variable values in supplied panel data contain only missing values for requested content area '", sgp.labels$my.subject, "' and grade '", rev(grade.progression)[1], "'.\n\t\t\tSimulation based standard errors/confidences intervals for SGPs wil not be calculated.\n"))
csem.tf <- FALSE
}
if (is.list(calculate.confidence.intervals) &&