-
Notifications
You must be signed in to change notification settings - Fork 0
/
poped.R
1946 lines (1889 loc) · 76.5 KB
/
poped.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
#' get the bpop number (which is a theta in PopED)
#'
#' @param theta name of the population parameter
#' @param ui rxode2 ui object
#' @return bpop[#] where # is the theta number
#' @noRd
#' @author Matthew L. Fidler
.popedGetBpopNum <- function(theta, ui) {
.iniDf <- ui$iniDf
.w <- which(.iniDf$name == theta)
if (length(.w) != 1) return(NA_character_)
if (is.na(.iniDf$ntheta[.w])) return(NA_character_)
paste0("bpop[", .iniDf$ntheta[.w], "]")
}
#' @export
rxUiGet.popedBpopRep <- function(x, ...) {
.ui <- x[[1]]
.split <- .ui$getSplitMuModel
.muRef <- c(.split$pureMuRef, .split$taintMuRef)
.thetas <- names(.muRef)
.covRefDf <- .ui$saemMuRefCovariateDataFrame
.ret <- data.frame(theta=.thetas,
bpop=vapply(.thetas, .popedGetBpopNum,
character(1), ui=.ui, USE.NAMES=FALSE),
mu=vapply(.thetas, .nonmemGetMuNum, character(1), ui=.ui,
USE.NAMES=FALSE),
cov=vapply(.thetas, .nonmemGetThetaMuCov, character(1),
ui=.ui, covRefDf=.covRefDf, USE.NAMES=FALSE))
.ret$b <- ifelse(is.na(.ret$mu), NA_character_,
paste0("b[",substr(.ret$mu,4, 10),"]"))
.iniDf <- .ui$iniDf
.w <- which(is.na(.iniDf$ntheta) &.iniDf$neta1 == .iniDf$neta2)
if (length(.w) > 0) {
.iniDf <- .iniDf[.w, ]
.var <- setNames(paste0("b[",.iniDf$neta1,"]"),.iniDf$name)
.ret$bpop <- vapply(seq_along(.ret$bpop), function(i) {
.v <- .ret$theta[i]
.b <- .var[.v]
if (!is.na(.b)) return(setNames(.b, NULL))
.ret$bpop[i]
}, character(1), USE.NAMES = FALSE)
}
.ret
}
attr(rxUiGet.popedBpopRep, "desc") <- "PopED data frame for replacements used in $popedFgFun"
#' @export
rxUiGet.popedFgFun <- function(x, ...) {
# function(x, a, bpop, b, bocc)
# x=?
# a=covariates (could be dose, tau etc)
# bpop = population variables
# b = eta variables
# bocc = occasion variables
.ui <- x[[1]]
.split <- .ui$getSplitMuModel
.mu <- rxUiGet.popedBpopRep(x, ...)
.ret <- vapply(seq_along(.mu$mu), function(i) {
if (is.na(.mu$mu[i])) return(NA_character_)
paste0(.mu$mu[i], " <- ", .mu$bpop[i],
ifelse(is.na(.mu$cov[i]), "",
paste0("+", .mu$cov[i])))
}, character(1), USE.NAMES=FALSE)
.ret <- .ret[!is.na(.ret)]
.mu2 <- ifelse(is.na(.mu$mu),
paste0(.mu$theta, "<-", .mu$bpop),
paste0(.mu$theta, "<-", .mu$mu, "+", .mu$b))
.covDef <- .ui$allCovs
.covDefLst <- lapply(seq_along(.covDef),
function(i) {
str2lang(paste0(.covDef[i], "<- a[", i + 1, "]"))
})
.iniDf <- .ui$iniDf
.w <- which(!is.na(.iniDf$ntheta) & !is.na(.iniDf$err))
.errTerm <- .iniDf$name[.w]
.errTermLst <- lapply(.w,
function(i) {
str2lang(paste0(.iniDf$name[i], " <- bpop[", .iniDf$ntheta[i], "]"))
})
.v <- c(.split$pureMuRef, .split$taintMuRef, .errTerm, .covDef)
.allCovs <- .ui$allCovs
.body1 <- c(list(quote(`{`)),
lapply(c(.ret, .mu2),
function(x) {
str2lang(x)
}),
.covDefLst,
.split$muRefDef,
.errTermLst,
list(str2lang(paste("c(ID=a[1],", paste(paste0(.v, "=", .v), collapse=","),
")"))))
.body1 <- as.call(.body1)
.f <- function(x, a, bpop, b, bocc) {}
body(.f) <- .body1
.f
}
attr(rxUiGet.popedFgFun, "desc") <- "PopED parameter model (fg_fun)"
.poped <- new.env(parent=emptyenv())
.poped$s <- NULL
.poped$modelNumber <- 1L
.poped$curNumber <- -1L
#' @export
rxUiGet.popedFfFun <- function(x, ...) {
.ui <- x[[1]]
.predDf <- .ui$predDf
if (length(.predDf$cond) == 1L) {
.body <- bquote({
.xt <- drop(xt)
.p <- p
.id <- .p[1]
.p <- .p[-1]
.totn <- length(.xt)
# unlike standard rxode2, parameters need not be named, but must be in the right order
if (.totn < .(.poped$maxn)) {
.p <- c(.p, .xt, seq(.(.poped$mt), by=0.1, length.out=.(.poped$maxn) - .totn))
.popedRxRunSetup(poped.db)
.ret <- nlmixr2est::.popedSolveIdN(.p, .xt, .id - 1L, .totn)
} else if (.totn > .(.poped$maxn)) {
.popedRxRunFullSetup(poped.db, .xt)
.ret <- nlmixr2est::.popedSolveIdN2(.p, .xt, .id - 1L, .totn)
} else {
.p <- c(.p, .xt)
.popedRxRunSetup(poped.db)
.ret <- nlmixr2est::.popedSolveIdN(.p, .xt, .id - 1L, .totn)
}
return(list(f=matrix(.ret$rx_pred_, ncol=1),
poped.db=poped.db))
})
.f <- function(model_switch, xt, p, poped.db){}
body(.f) <- .body
.f
} else {
.body <- bquote({
.xt <- drop(xt)
.id <- p[1]
.p <- p[-1]
.u <- .xt
.lu <- length(.u)
.totn <- length(.xt)
# unlike standard rxode2, parameters need not be named, but must be in the right order
if (.lu < .(.poped$maxn)) {
.p <- c(.p, .u, seq(.(.poped$mt), by=0.1, length.out=.(.poped$maxn) - .lu))
.popedRxRunSetup(poped.db)
.ret <- nlmixr2est::.popedSolveIdME(.p, .u, .xt, model_switch, .(length(.predDf$cond)),
.id - 1, .totn)
} else if (.lu > .(.poped$maxn)) {
.popedRxRunFullSetupMe(poped.db, .xt, model_switch)
.ret <- nlmixr2est::.popedSolveIdME2(.p, .u, .xt, model_switch, .(length(.predDf$cond)),
.id - 1, .totn)
} else {
.p <- c(.p, .u)
.popedRxRunSetup(poped.db)
.ret <- nlmixr2est::.popedSolveIdME(.p, .u, .xt, model_switch, .(length(.predDf$cond)),
.id - 1L, .totn)
}
return(list(f=matrix(.ret$rx_pred_, ncol=1),
poped.db=poped.db))
})
.f <- function(model_switch, xt, p, poped.db){}
body(.f) <- .body
.f
}
}
attr(rxUiGet.popedFfFun, "desc") <- "PopED parameter model (ff_fun)"
## @export
## rxUiGet.popedModel <- function(x, ...) {
## ui <- x[[1]]
## ## list(model=list(ff_pointer=rxUiGet.popedFfFun(x, ...),
## ## fg_pointer=rxUiGet.popedFgFun(x, ...),
## ## ferror_pointer=rxUiGet.popedFErrorFun(x, ...),
## ## auto_pointer=rxode2::rxGetControl(ui, "auto_pointer", ""),
## ## user_distribution_pointer=rxode2::rxGetControl(ui, "user_distribution_pointer", "")))
##}
#' Get the weight from the rxode2 solve
#'
#' This shouldn't be called directly
#'
#' @param popedDb poped DB with babelmixr2 issue
#'
#' @return rxode2 weights for the poped error function
#' @export
#' @author Matthew L. Fidler
#' @keywords internal
.popedW <- function(popedDb) {
sqrt(popedDb$babelmixr2$s[["w"]])
}
#' Get the function value from the rxode2 solve
#'
#' This shouldn't be called directly
#'
#' @inheritParams .popedW
#'
#' @return rxode2 weights for the poped error function
#' @export
#' @author Matthew L. Fidler
#' @keywords internal
.popedF <- function(popedDb) {
popedDb$babelmixr2$s[["rx_pred_"]]
}
#' Setup poped if needed
#'
#' Should not be called by user
#'
#' @return nothing, called for side effects
#' @export
#' @author Matthew L. Fidler
#' @keywords internal
.popedRxRunSetup <- function(popedDb) {
if (!rxode2::rxSolveSetup()) {
.poped$setup <- 0L
}
if (.poped$curNumber != popedDb$babelmixr2$modelNumber) {
.poped$setup <- 0L
}
if (.poped$setup != 1L) {
rxode2::rxSolveFree()
nlmixr2est::.popedSetup(popedDb$babelmixr2, FALSE)
.poped$setup <- 1L
.poped$curNumber <- popedDb$babelmixr2$modelNumber
.poped$fullXt <- NULL
}
invisible()
}
#' Setup a full solve for a multiple-endpoint model
#'
#' @param popedDb poped database
#' @param xt design times
#' @param ms model switch indicator
#' @return nothing, called for side effects
#' @noRd
#' @author Matthew L. Fidler
.popedRxRunFullSetupMe <- function(popedDb, xt, ms) {
if (!rxode2::rxSolveSetup()) {
.poped$setup <- 0L
}
if (.poped$curNumber != popedDb$babelmixr2$modelNumber) {
.poped$setup <- 0L
}
if (.poped$setup == 2L) {
if (!identical(.poped$fullXt, length(xt))) {
.poped$setup <- 0L
}
}
if (.poped$setup != 2L) {
rxode2::rxSolveFree()
.e <- popedDb$babelmixr2
.dat <- with(.e$dataF0lst,
do.call(rbind,
lapply(.e$uid,
function(id) {
.data <- .e$dataF0[.e$dataF0[[.wid]] == id &
.e$dataF0[[.wevid]] != 0,, drop = FALSE]
.len <- length(.data[[.wid]])
if (.len == 0) {
.data2 <- .e$dataF00
} else {
.data2 <- .data[.len, ]
}
.data2[[.wevid]] <- 0
if (length(.wamt) == 1L) .data2[[.wamt]] <- NA
if (length(.wrate) == 1L) .data2[[.wrate]] <- NA
if (length(.wdur) == 1L) .data2[[.wdur]] <- NA
if (length(.wss) == 1L) .data2[[.wss]] <- NA
if (length(.wii) == 1L) .data2[[.wii]] <- NA
if (length(.waddl) == 1L) .data2[[.waddl]] <- NA
.data3 <- do.call(rbind,
lapply(xt,
function(t) {
.d <- .data2
.d[[.wtime]] <- t
.d
}))
rbind(.data, .data3)
})))
.et <- rxode2::etTrans(.dat, .e$modelF)
.e$dataF <- .et
nlmixr2est::.popedSetup(.e, TRUE)
.poped$fullXt <- length(xt)
.poped$curNumber <- popedDb$babelmixr2$modelNumber
.poped$setup <- 2L
}
}
#' Setup for a full solve with a single endpoint model
#'
#'
#' @param popedDb Poped database
#' @param xt design times
#' @return nothing, called for side effects
#' @noRd
#' @author Matthew L. Fidler
.popedRxRunFullSetup <- function(popedDb, xt) {
# For PopED simply assume same number of xt = same problem
# reasonable assumption?
if (!rxode2::rxSolveSetup()) {
.poped$setup <- 0L
}
if (.poped$curNumber != popedDb$babelmixr2$modelNumber) {
.poped$setup <- 0L
}
if (.poped$setup == 2L) {
if (!identical(.poped$fullXt, length(xt))) {
.poped$setup <- 0L
}
}
if (.poped$setup != 2L) {
rxode2::rxSolveFree()
.e <- popedDb$babelmixr2
.dat <- with(.e$dataF0lst,
do.call(rbind,
lapply(.e$uid,
function(id) {
.data <- .e$dataF0[.e$dataF0[[.wid]] == id &
.e$dataF0[[.wevid]] != 0, ]
.len <- length(.data[[.wid]])
.data2 <- .data[.len, ]
.data2[[.wevid]] <- 0
if (length(.wamt) == 1L) .data2[[.wamt]] <- NA
if (length(.wrate) == 1L) .data2[[.wrate]] <- NA
if (length(.wdur) == 1L) .data2[[.wdur]] <- NA
if (length(.wss) == 1L) .data2[[.wss]] <- NA
if (length(.wii) == 1L) .data2[[.wii]] <- NA
if (length(.waddl) == 1L) .data2[[.waddl]] <- NA
.data3 <- do.call(rbind,
lapply(xt,
function(t) {
.d <- .data2
.d[[.wtime]] <- t
.d
}))
rbind(.data, .data3)
})))
.et <- rxode2::etTrans(.dat, .e$modelF)
.e$dataF <- .et
nlmixr2est::.popedSetup(.e, TRUE)
.poped$fullXt <- length(xt)
.poped$curNumber <- popedDb$babelmixr2$modelNumber
.poped$setup <- 2L
}
}
#' This gets the epsi associated with the nlmixr2/rxode2 model specification
#'
#' @param ui rxode2 ui model
#' @param cnd condition to explore (ie, cp, eff, etc, defined in the
#' predDf ui data frame)
#' @param type Type of parameter to query (add, prop, pow etc).
#' @return the eps[,#] as a string, though there are side effects of
#' incrementing the epsi number as well as adding the variance
#' estimates to $sigmaEst.
#' @noRd
#' @author Matthew L. Fidler
.getVarCnd <- function(ui, cnd, type) {
.iniDf <- ui$iniDf
.w <- which(.iniDf$condition == cnd & .iniDf$err == type)
if (length(.w) != 1L) stop("could not determine cnd: ", cnd, " type: ", type, " for error model")
.iniDf <- .iniDf[.w, ]
.eta <- .poped$eta + 1
.n <- .iniDf$name
.est <- c(.poped$etaEst, setNames(c(.iniDf$est^2), .n))
.poped$etaNotfixed <- c(.poped$etaNotfixed,
setNames(1L - .iniDf$fix * 1L, .n))
.poped$etaEst <- .est
.poped$eta <- .eta
return(paste0("epsi[,", .eta, "]"))
}
#' Get additive error
#'
#' @param ui rxode2 ui model
#' @param pred1 one row of the $predDf data frame
#' @return The parsed line of a model function
#' @noRd
#' @author Matthew L. Fidler
.popedGetErrorModelAdd <- function(ui, pred1) {
str2lang(paste0("rxErr", pred1$dvid, " <- rxF + ", .getVarCnd(ui, pred1$cond, "add")))
}
#' Get proportional error
#'
#' @param ui rxode2 ui model
#' @param pred1 one row of the $predDf data frame
#' @return The parsed line of a model function
#' @noRd
#' @author Matthew L. Fidler
.popedGetErrorModelProp <- function(ui, pred1) {
str2lang(paste0("rxErr", pred1$dvid, " <- rxF * (1 + ", .getVarCnd(ui, pred1$cond, "prop"), ")"))
}
#' Get power error
#'
#' @param ui rxode2 ui model
#' @param pred1 one row of the $predDf data frame
#' @return The parsed line of a model function
#' @noRd
#' @author Matthew L. Fidler
.popedGetErrorModelPow <- function(ui, pred1) {
# Could be in the F anyway, need to check
stop("pow() not implemented yet")
}
#' Get add+prop (type 2 error)
#'
#' @param ui rxode2 ui model
#' @param pred1 one row of the $predDf data frame
#' @return The parsed line of a model function
#' @noRd
#' @author Matthew L. Fidler
.popedGetErrorModelAddProp <- function(ui, pred1) {
str2lang(paste0("rxErr", pred1$dvid, " <- rxF*(1+", .getVarCnd(ui, pred1$cond, "prop"),
") + ", .getVarCnd(ui, pred1$cond, "add")))
}
#' Get add+pow (type 2 error)
#'
#' @param ui rxode2 ui model
#' @param pred1 one row of the $predDf data frame
#' @return The parsed line of a model function
#' @noRd
#' @author Matthew L. Fidler
.popedGetErrorModelAddPow <- function(ui, pred1) {
# Could be in the F anyway, need to check
stop("pow() not implemented yet")
}
# When the error isn't specified (probably a log-likelihood)
.popedGetErrorModelNone <- function(ui, pred1) {
stop("error model could not be interpreted as a PopED model")
}
.popedGetErrorModel <- function(ui, pred1) {
switch(as.character(pred1$errType),
"add"=.popedGetErrorModelAdd(ui, pred1), # 1
"prop"=.popedGetErrorModelProp(ui, pred1), # 2
"pow"=.popedGetErrorModelPow(ui, pred1), # 3
"add + prop"=.popedGetErrorModelAddProp(ui, pred1),# 4
"add + pow"=.popedGetErrorModelAddPow(ui, pred1), # 5
"none"=.popedGetErrorModelNone(ui, pred1))
}
#'@export
rxUiGet.popedFErrorFun <- function(x, ...) {
.ui <- x[[1]]
if (rxode2::rxGetControl(.ui, "fixRes", FALSE)) {
f <- function(model_switch, xt, parameters, epsi, poped.db) {
# Will assign in babelmixr2 namespace
do.call(poped.db$model$ff_pointer,list(model_switch,xt,parameters,poped.db))
y <- .popedF(poped.db) + .popedW(poped.db) * epsi[, 1]
return(list(y=y,poped.db=poped.db))
}
return(f)
} else {
.poped$eta <- 0
.poped$etaEst <- NULL
.poped$etaNotfixed <- NULL
.predDf <- .ui$predDf
.ret <- lapply(seq_along(.predDf$cond),
function(c) {
.popedGetErrorModel(.ui, .predDf[c, ])
})
.lret <- length(.ret)
.ret <- c(list(
quote(`{`),
str2lang("rxReturnArgs <- do.call(poped.db$model$ff_pointer,list(model_switch,xt,parameters,poped.db)) "),
str2lang("rxF <- rxReturnArgs[[1]]")),
str2lang("rxPoped.db <- rxReturnArgs[[2]]"),
.ret)
.f <- function(model_switch, xt, parameters, epsi, poped.db) {}
if (.lret == 1) {
# single endpoint model
.ret <- c(.ret,
list(str2lang("return(list(y=rxErr1,poped.db=rxPoped.db))")))
} else {
# multiple endpoint model, use model_switch
.ret <- c(.ret,
lapply(seq_len(.lret),
function(i) {
str2lang(paste0("rxF[rxPoped.db$babelmixr2$we[[", i,
"]]] <- rxErr", i, "[rxPoped.db$babelmixr2$we[[", i, "]]]"))
}),
list(str2lang("return(list(y=rxF, poped.db=rxPoped.db))")))
}
.ret <- as.call(.ret)
body(.f) <- .ret
return(.f)
}
}
attr(rxUiGet.popedFErrorFun, "desc") <- "PopED error function(fError_fun)"
#' @export
rxUiGet.popedRxmodelBase <- function(x, ...) {
.ui <- x[[1]]
.ui <- rxode2::rxUiDecompress(.ui)
.split <- .ui$getSplitMuModel
.model2 <- .split$modelWithDrop
.w <- which(vapply(seq_along(.model2),
function(i) {
!identical(.model2[[i]], quote(`_drop`))
}, logical(1), USE.NAMES=FALSE))
.model2 <- .model2[.w]
.model2 <- vapply(seq_along(.model2),
function(i) {
deparse1(.model2[[i]])
}, character(1), USE.NAMES = FALSE)
.ui2 <- rxode2::rxUiDecompress(.ui)
# test edge cases of all thetas and no thetas
.theta <- .ui$iniDf[!is.na(.ui$iniDf$ntheta), "name"]
.eta <- .ui$iniDf[which(.ui$iniDf$neta1 == .ui$iniDf$neta2), "name"]
.pars <- c(.theta, .eta)
.pars <- paste0("rxDummy", .pars, " <- ", .pars)
.model2 <- c(.pars,
.model2)
suppressMessages(suppressWarnings(model(.ui2) <- .model2))
.ui2 <- rxode2::rxUiDecompress(.ui2)
.errLines <- nlmixr2est::rxGetDistributionFoceiLines(.ui2)
.multi <- FALSE
if (length(.errLines) > 1L) {
.multi <- TRUE
.errLines <- lapply(seq_along(.errLines),
function(i) {
c(.errLines[[i]],
list(str2lang(paste0("rx_pred_", i, " <- rx_pred_")),
str2lang(paste0("rx_r_", i, " <- rx_r_"))))
})
}
.mod <- rxode2::rxCombineErrorLines(.ui2, errLines=.errLines,
cmtLines=FALSE, dvidLine=FALSE, useIf = FALSE)
## .mod <- rxode2::rxCombineErrorLines(.ui2, errLines=popedErr(.ui2),
## cmtLines=FALSE, dvidLine=FALSE, useIf = FALSE)
.mod <- .mod[[2]]
.mod <- as.list(.mod[seq_along(.mod)[-1]])
# drop dummy and params()
.w <- which(vapply(seq_along(.mod),
function(i) {
if (i == 1) return(FALSE)
.cur <- .mod[[i]]
if (identical(.cur[[1]], quote(`<-`))) {
.lhs <- deparse1(.cur[[2]])
if (substr(.lhs, 1, 7) == "rxDummy") {
return(FALSE)
}
}
TRUE
},
logical(1), USE.NAMES = FALSE))
.mod <- .mod[.w]
.mod <- lapply(seq_along(.mod),
function(i) {
.cur <- .mod[[i]]
if (identical(.cur[[1]], quote(`<-`)) ||
identical(.cur[[1]], quote(`=`))) {
.v <- deparse1(.cur[[2]])
if (length(.cur[[2]]) == 1L &&
!grepl("^rx_(pred|r)_[0-9]+$", .v)) {
.cur[[1]] <- quote(`~`)
}
}
if (!.multi && identical(.cur[[1]], quote(`~`))) {
if (identical(.cur[[2]], quote(`rx_pred_`)) ||
identical(.cur[[2]], quote(`rx_r_`)))
.cur[[1]] <- quote(`<-`)
}
.cur
})
.mod
}
attr(rxUiGet.popedRxmodelBase, "desc") <- "This gets the base rxode2 model for PopED"
#' Get PopEd's rxode2 model (unevaluated)
#'
#' This is an internal function and really shouldn't be called directly
#'
#' @param ui User interface
#'
#' @param maxNumTime Maximum number of evaluation times used in model
#' (usually these are design points). They are implemented as
#' modeling times. Note when there are modeling times present, you
#' cannot use the faster solving method (though slow solving still
#' works)
#'
#' @return unevaluated rxode2 model with 2 attributes:
#'
#' - First attribute is "mtime", which tells if the modeled times
#' represent design points (boolean)
#'
#' - Second attribute is "maxNumTime", which tells the maximum number
#' of design points present in this model (integerish)
#'
#' @noRd
#' @keywords internal
#' @author Matthew L. Fidler
.popedRxModel <- function(ui, maxNumTime=2) {
checkmate::testIntegerish(maxNumTime, lower=1, len=1)
.base <- rxUiGet.popedRxmodelBase(list(ui))
.base2 <- eval(as.call(c(list(quote(`rxModelVars`)),
as.call(c(list(quote(`{`)), .base)))))
if (.base2$nMtime > 0L) {
.minfo("mtime() detected in model, slower solving used")
.ret <- as.call(c(list(quote(`rxode2`)),
as.call(c(list(quote(`{`)), .base))))
attr(.ret, "mtime") <- FALSE
attr(.ret, "maxNumTime") <- 0L
return(.ret)
}
.split <- ui$getSplitMuModel
.covDef <- ui$allCovs
.iniDf <- ui$iniDf
.w <- which(!is.na(.iniDf$ntheta) & !is.na(.iniDf$err))
.errTerm <- .iniDf$name[.w]
.poped$paramF <- c(.split$pureMuRef, .split$taintMuRef, .errTerm,
.covDef)
.poped$paramMT <- c(.poped$paramF, paste0("rxXt_", seq_len(maxNumTime)))
.param0 <- str2lang(paste0("params(", paste(.poped$paramF, collapse=","), ")"))
.param <- str2lang(paste0("params(", paste(.poped$paramMT, collapse=","), ")"))
.poped$paramF <- setNames(rep(1, length(.poped$paramF)), .poped$paramF)
.poped$paramMT <- setNames(rep(1, length(.poped$paramMT)), .poped$paramMT)
.ret0 <- as.call(c(list(quote(`rxode2`)),
as.call(c(list(quote(`{`), .param0),
.base))))
.poped$modelF <- eval(.ret0) # Full model
.ret <- as.call(c(list(quote(`rxode2`)),
as.call(c(list(quote(`{`), .param),
.base,
lapply(seq_len(maxNumTime),
function(i) {
str2lang(sprintf("mtime(rxXt_%d_v) ~ rxXt_%d", i, i))
})))))
attr(.ret, "mtime") <- TRUE
attr(.ret, "maxNumTime") <- maxNumTime
.ret
}
#' @export
rxUiGet.popedBpop <- function(x, ...) {
.ui <- x[[1]]
.iniDf <- .ui$iniDf
.bpop <- .iniDf[!is.na(.ui$iniDf$ntheta), ]
setNames(.bpop$est, .bpop$name)
}
attr(rxUiGet.popedBpop, "desc") <- "Get PopED's $bpop"
#' @export
rxUiGet.popedNotfixedBpop <- function(x, ...) {
.ui <- x[[1]]
.iniDf <- .ui$iniDf
.bpop <- .iniDf[!is.na(.ui$iniDf$ntheta), ]
# Residual errors are "fixed" parameters
.bpop$fix[!is.na(.bpop$err)] <- TRUE
1 - .bpop$fix * 1
}
attr(rxUiGet.popedNotfixedBpop, "desc") <- "Get PopED's $notfixed_bpop"
## Omega matrix specification
#' @export
rxUiGet.popedD <- function(x, ...) {
.ui <- x[[1]]
.omega <- .ui$omega
# does it have to have the mu-referenced named (just like examples?)
diag(.omega)
}
attr(rxUiGet.popedD, "desc") <- "Get PopED's $d parameter"
#' @export
rxUiGet.popedCovd <- function(x, ...) {
.ui <- x[[1]]
.omega <- .ui$omega
.ret <- .omega[lower.tri(.omega)]
names(.ret) <- NULL
if (all(.ret == 0)) return(NULL)
.ret
}
attr(rxUiGet.popedCovd, "desc") <- "Get PopED's $covd parameter"
#' @export
rxUiGet.popedNotfixedD <- function(x, ...) {
.ui <- x[[1]]
.iniDf <- .ui$iniDf
.iniDf <- .iniDf[which(is.na(.iniDf$ntheta) & .iniDf$neta1 == .iniDf$neta2), ]
.ret <- 1 - .iniDf$fix * 1
if (all(.ret == 1)) return(NULL)
.ret
}
attr(rxUiGet.popedNotfixedD, "desc") <- "Get PopED's $notfixed_d"
#' @export
rxUiGet.popedNotfixedCovd <- function(x, ...) {
.ui <- x[[1]]
.iniDf <- .ui$iniDf
.lotri <- lotri::as.lotri(.iniDf)
.lotriFix <- attr(.lotri,"lotriFix")
if (is.null(.lotriFix)) {
return(NULL)
}
.ret <- .lotriFix[lower.tri(.lotriFix)]
names(.ret) <- NULL
if (all(.ret == 0)) return(NULL)
1 - .ret * 1
}
attr(rxUiGet.popedNotfixedCovd, "desc") <- "Get PopED's $notfixed_covd"
#' @export
rxUiGet.popedSigma <- function(x, ...) {
.ui <- x[[1]]
if (rxode2::rxGetControl(.ui, "fixRes", FALSE)) {
return(1.0)
} else {
rxUiGet.popedFErrorFun(x, ...) # called for side effect
return(.poped$etaEst)
}
}
attr(rxUiGet.popedSigma, "desc") <- "PopED database $sigma"
#' @export
rxUiGet.popedNotfixedSigma <- function(x, ...) {
.ui <- x[[1]]
if (rxode2::rxGetControl(.ui, "fixRes", FALSE)) {
return(0L)
} else {
rxUiGet.popedFErrorFun(x, ...) # called for side effect
return(.poped$etaNotfixed)
}
}
attr(rxUiGet.popedNotfixedSigma, "desc") <- "PopED database $notfixed_sigma"
#' Create a babelmixr2/nlmixr2 design space based on a data frame
#'
#' From the dataset construct `xt`, `minxt`, `maxxt` and `a`
#'
#' This does not work with time-varying covariates. (FIXME check)
#'
#' This needs to be calculated before getting the design functions so
#' that different size designs can be padded
#'
#' @param ui rxode2 ui object
#' @param data babelmixr2 design data, very similar to a rxode2 modeling dataset
#' @param time string that represents the time in the dataset (ie xt)
#' @param timeLow string that represents the lower design time (ie minxt)
#' @param timeHi string that represents the upper design time (ie maxmt)
#' @param id The id variable
#' @param fixRes boolean; Fix the residuals to what is specified by the model
#' @inheritParams PopED::create_design
#' @inheritParams PopED::create_design_space
#' @return PopED design space
#' @noRd
#' @author Matthew L. Fidler
.popedDataToDesignSpace <- function(ui, data, groupsize=NULL, time="time", timeLow="low", timeHi="high",
id="id",
a=NULL,
maxa=NULL,
mina=NULL,
m = NULL, x = NULL, ni = NULL,
maxni = NULL,
minni = NULL,
maxtotni = NULL,
mintotni = NULL,
maxgroupsize = NULL,
mingroupsize = NULL,
maxtotgroupsize = NULL,
mintotgroupsize = NULL,
xt_space = NULL,
a_space = NULL,
x_space = NULL,
use_grouped_xt = FALSE,
grouped_xt = NULL,
use_grouped_a = FALSE,
grouped_a = NULL,
use_grouped_x = FALSE,
grouped_x = NULL,
our_zero = NULL,
maxn=NULL) {
rxode2::rxSolveFree()
rxode2::rxReq("PopED")
data <- as.data.frame(data)
ui <- rxode2::assertRxUi(ui)
groupsize <- rxode2::rxGetControl(ui, "groupsize", groupsize)
if (is.null(groupsize)) {
.minfo("groupsize should be specified; but for now assuming 20")
groupsize <- 20
}
# Get from assigned control inside of ui object
for (opt in c("m", "x","ni", "maxni","minni", "maxtotni",
"mintotni", "maxgroupsize","mingroupsize","maxtotgroupsize", "mintotgroupsize",
"xt_space", "a", "maxa", "mina",
"a_space", "x_space", "grouped_xt", "use_grouped_a",
"grouped_a", "grouped_x", "our_zero", "use_grouped_xt",
"use_grouped_a", "use_grouped_x", "maxn")) {
assign(opt, rxode2::rxGetControl(ui, opt, get(opt)))
}
.et <- rxode2::etTrans(data, ui)
.tmp <- attr(class(.et),".rxode2.lst")
class(.tmp) <- NULL
.a <- as.matrix(.tmp$cov1)
.allCovs <- ui$allCovs
.need <- setdiff(.allCovs, c("ID", colnames(.a)))
if (length(.need) > 0) {
if (is.null(a)) {
} else if (is.list(a)) {
if (length(.a[, "ID"]) != 1) {
stop("when optimizing design elements, only one ID in the input data can be used",
call.=FALSE)
}
.a <- setNames(as.vector(.a),colnames(.a))
.a <- lapply(seq_along(a),
function(i) {
c(.a, a[[i]])
})
.need <- setdiff(.allCovs, names(.a[[1]]))
if (length(.need) > 0) {
stop("covariates in model but not defined: ", paste(.need, collapse=", "),
call.=FALSE)
}
if (is.null(use_grouped_xt)) {
.minfo("assuming same times for each group (use_grouped_xt=TRUE)")
use_grouped_xt <- TRUE
}
if (is.null(m)) {
m <- length(.a)
.minfo(paste0("assuming group size m=", m))
}
if (!is.null(maxa)) {
maxa <- c(ID=1, maxa)
}
if (!is.null(mina)) {
mina <- c(ID=1, mina)
}
} else {
stop()
}
} else {
.a <- .a[, c("ID", .allCovs)]
}
.nd <- tolower(names(data))
.data <- data
.wevid <- which(.nd == "evid")
if (length(.wevid) == 0L) {
.minfo("could not find evid, assuming all are design points")
.data$evid <- 0
}
.wtime <- which(.nd == time)
if (length(.wtime) != 1L) {
stop(paste0("could not find the required data item: ", time),
call.=FALSE)
}
.wid <- which(.nd == id)
if (length(.wid) == 0L) {
.data$id <- 1L
.nd <- names(.data)
.wid <- which(.nd == id)
} else if (length(.wid) != 1L) {
stop("duplicate ids found",
call.=FALSE)
}
.env <- new.env(parent=emptyenv())
.env$mt <- -Inf
.wcmt <- which(.nd == "cmt")
.wdvid <- which(.nd == "dvid")
.multipleEndpoint <- FALSE
.poped$uid <- unique(.data[[.wid]])
if (length(ui$predDf$cond) > 1L) {
.multipleEndpoint <- TRUE
.xt <- lapply(.poped$uid,
function(id) {
do.call(rbind,
lapply(seq_along(ui$predDf$cond),
function(i) {
.data <- .data[.data[[.wid]] == id &
.data[[.wevid]] == 0, ]
.time <- .data[[.wtime]]
.env$mt <- max(c(.time, .env$mt))
if (length(.wdvid) == 1L) {
.wd <- which(.data[[.wdvid]] == i)
if (length(.wd) == 0) .wd <- which(.data[[.wdvid]] == ui$predDf$cond[i])
if (length(.wd) > 0) {
.time <- .time[.wd]
return(data.frame(time=.time, dvid=i))
}
}
# could not find dvid spec, try cmt spec
if (length(.wcmt) == 1L) {
.wd <- which(.data[[.wcmt]] == ui$predDf$cmt[i])
if (length(.wd) == 0) {
.wd <- which(.data[[.wcmt]] == ui$predDf$cond[i])
}
if (length(.wd) > 0) {
.time <- .time[.wd]
return(data.frame(time=.time, dvid=i))
}
}
stop(paste0("multiple endpoint design dataset needs either dvid/cmt for design points; missing at least '", ui$predDf$cond[i], "'"),
call.=FALSE)
}))
})
} else {
.xt <- lapply(.poped$uid,
function(id) {
.data <- .data[.data[[.wid]] == id &
.data[[.wevid]] == 0, ]
.ret <- .data[[.wtime]]
.env$mt <- max(c(.ret, .env$mt))
.ret
})
}
.single <- FALSE
.modelSwitch <- NULL
if (length(.xt) == 1L) {
if (.multipleEndpoint) {
.xt <- .xt[[1]]
.modelSwitch <- .xt$dvid
.xt <- .xt$time
} else {
.xt <- .xt[[1]]
}
.single <- TRUE
}
if (length(ui$predDf$cond) > 1L) {
.design <- PopED::create_design(xt=.xt,
groupsize=groupsize,
m = m, x = x, a = .a, ni = ni,
model_switch = .modelSwitch)
} else {
.design <- PopED::create_design(xt=.xt,
groupsize=groupsize,
m = m, x = x, a = .a, ni = ni,
model_switch = NULL)
}
.wlow <- which(.nd == timeLow)
.minxt <- NULL
if (length(.wlow) == 1L) {
.minxt <- lapply(.poped$uid,
function(id) {
.data <- .data[.data[[.wid]] == id &
.data[[.wevid]] == 0, ]
.ret <- .data[[.wlow]]
.env$mt <- max(c(.ret, .env$mt))
.ret
})
if (.single) .minxt <- .minxt[[1]]
}
.whi <- which(.nd == timeHi)
.maxxt <- NULL
if (length(.whi) == 1L) {
.maxxt <- lapply(.poped$uid,
function(id) {
.data <- .data[.data[[.wid]] == id &
.data[[.wevid]] == 0, ]
.ret <- .data[[.whi]]
.env$mt <- max(c(.ret, .env$mt))
.ret
})
if (.single) .maxxt <- .maxxt[[1]]
}
.designSpace <-
PopED::create_design_space(.design,
maxni = maxni,
minni = minni,
maxtotni = maxtotni,
mintotni = mintotni,
maxgroupsize = maxgroupsize,
mingroupsize = mingroupsize,
maxtotgroupsize = maxtotgroupsize,
mintotgroupsize = mintotgroupsize,
maxxt=.maxxt,
minxt=.minxt,
xt_space = xt_space,
mina = mina,
maxa = maxa,
a_space = a_space,
x_space = x_space,
use_grouped_xt = use_grouped_xt,
grouped_xt = grouped_xt,
use_grouped_a = use_grouped_a,
grouped_a = grouped_a,
use_grouped_x = use_grouped_x,
grouped_x = grouped_x,
our_zero = our_zero)
if (checkmate::testIntegerish(maxn, lower=1, any.missing=FALSE, len=1)) {
.poped$maxn <- maxn
} else {
.poped$maxn <- max(.designSpace$design$ni)*length(ui$predDf$cond)
}
.rx <- .popedRxModel(ui, maxNumTime=.poped$maxn)
if (!attr(.rx, "mtime")) {
stop("mtime models are not supported yet",
call.=FALSE)
}
.poped$mt <- .env$mt + 0.1
.rx <- eval(.rx)
.poped$modelMT <- .rx
.wamt <- which(.nd == "amt")
.wrate <- which(.nd == "rate")
.wdur <- which(.nd == "dur")
.wss <- which(.nd == "ss")
.wii <- which(.nd == "ii")
.waddl <- which(.nd == "addl")
# Create an empty database for solving > number of MT defined
.poped$dataF00 <- .data[1, ]