/
nlm.R
899 lines (840 loc) · 29.5 KB
/
nlm.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
#' nlmixr2 defaults controls for nlm
#'
#' @inheritParams stats::nlm
#' @inheritParams foceiControl
#' @inheritParams saemControl
#' @param covMethod allows selection of "r", which uses nlmixr2's
#' `nlmixr2Hess()` for the hessian calculation or "nlm" which uses
#' the hessian from `stats::nlm(.., hessian=TRUE)`. When using
#' `nlmixr2's` hessian for optimization or `nlmixr2's` gradient for
#' solving this defaults to "nlm" since `stats::optimHess()` assumes
#' an accurate gradient and is faster than `nlmixr2Hess`
#' @param returnNlm is a logical that allows a return of the `nlm`
#' object
#' @param solveType tells if `nlm` will use nlmixr2's analytical
#' gradients when available (finite differences will be used for
#' event-related parameters like parameters controlling lag time,
#' duration/rate of infusion, and modeled bioavailability). This can
#' be:
#'
#' - `"hessian"` which will use the analytical gradients to create a
#' Hessian with finite differences.
#'
#' - `"gradient"` which will use the gradient and let `nlm` calculate
#' the finite difference hessian
#'
#' - `"fun"` where nlm will calculate both the finite difference
#' gradient and the finite difference Hessian
#'
#' When using nlmixr2's finite differences, the "ideal" step size for
#' either central or forward differences are optimized for with the
#' Shi2021 method which may give more accurate derivatives
#'
#' @param shiErr This represents the epsilon when optimizing the ideal
#' step size for numeric differentiation using the Shi2021 method
#'
#' @param hessErr This represents the epsilon when optimizing the
#' Hessian step size using the Shi2021 method.
#'
#' @param shi21maxHess Maximum number of times to optimize the best
#' step size for the hessian calculation
#'
#' @param gradTo this is the factor that the gradient is scaled to
#' before optimizing. This only works with
#' scaleType="nlmixr2".
#'
#' @return nlm control object
#' @export
#' @author Matthew L. Fidler
#' @examples
#'
#' \donttest{
#' # A logit regression example with emax model
#'
#' dsn <- data.frame(i=1:1000)
#' dsn$time <- exp(rnorm(1000))
#' dsn$DV=rbinom(1000,1,exp(-1+dsn$time)/(1+exp(-1+dsn$time)))
#'
#' mod <- function() {
#' ini({
#' E0 <- 0.5
#' Em <- 0.5
#' E50 <- 2
#' g <- fix(2)
#' })
#' model({
#' v <- E0+Em*time^g/(E50^g+time^g)
#' ll(bin) ~ DV * v - log(1 + exp(v))
#' })
#' }
#'
#' fit2 <- nlmixr(mod, dsn, est="nlm")
#'
#' print(fit2)
#'
#' # you can also get the nlm output with fit2$nlm
#'
#' fit2$nlm
#'
#' # The nlm control has been modified slightly to include
#' # extra components and name the parameters
#' }
nlmControl <- function(typsize = NULL,
fscale = 1, print.level = 0, ndigit = NULL, gradtol = 1e-6,
stepmax = NULL,
steptol = 1e-6, iterlim = 10000, check.analyticals = FALSE,
returnNlm=FALSE,
solveType=c("hessian", "grad", "fun"),
stickyRecalcN=4,
maxOdeRecalc=5,
odeRecalcFactor=10^(0.5),
eventType=c("central", "forward"),
shiErr=(.Machine$double.eps)^(1/3),
shi21maxFD=20L,
optimHessType=c("central", "forward"),
hessErr =(.Machine$double.eps)^(1/3),
shi21maxHess=20L,
useColor = crayon::has_color(),
printNcol = floor((getOption("width") - 23) / 12), #
print = 1L, #
normType = c("rescale2", "mean", "rescale", "std", "len", "constant"), #
scaleType = c("nlmixr2", "norm", "mult", "multAdd"), #
scaleCmax = 1e5, #
scaleCmin = 1e-5, #
scaleC=NULL,
scaleTo=1.0,
gradTo=1.0,
rxControl=NULL,
optExpression=TRUE, sumProd=FALSE,
literalFix=TRUE,
addProp = c("combined2", "combined1"),
calcTables=TRUE, compress=TRUE,
covMethod=c("r", "nlm", ""),
adjObf=TRUE, ci=0.95, sigdig=4, sigdigTable=NULL, ...) {
checkmate::assertNumeric(shiErr, lower=0, any.missing=FALSE, len=1)
checkmate::assertNumeric(hessErr, lower=0, any.missing=FALSE, len=1)
checkmate::assertIntegerish(shi21maxFD, lower=1, any.missing=FALSE, len=1)
checkmate::assertIntegerish(shi21maxHess, lower=1, any.missing=FALSE, len=1)
checkmate::assertLogical(optExpression, len=1, any.missing=FALSE)
checkmate::assertLogical(literalFix, len=1, any.missing=FALSE)
checkmate::assertLogical(sumProd, len=1, any.missing=FALSE)
checkmate::assertNumeric(stepmax, lower=0, len=1, null.ok=TRUE, any.missing=FALSE)
checkmate::assertIntegerish(print.level, lower=0, upper=2, any.missing=FALSE)
checkmate::assertNumeric(ndigit, lower=0, len=1, any.missing=FALSE, null.ok=TRUE)
checkmate::assertNumeric(gradtol, lower=0, len=1, any.missing=FALSE)
checkmate::assertNumeric(steptol, lower=0, len=1, any.missing=FALSE)
checkmate::assertIntegerish(iterlim, lower=1, len=1, any.missing=FALSE)
checkmate::assertLogical(check.analyticals, len=1, any.missing=FALSE)
checkmate::assertLogical(returnNlm, len=1, any.missing=FALSE)
checkmate::assertLogical(calcTables, len=1, any.missing=FALSE)
checkmate::assertLogical(compress, len=1, any.missing=TRUE)
checkmate::assertLogical(adjObf, len=1, any.missing=TRUE)
.xtra <- list(...)
.bad <- names(.xtra)
.bad <- .bad[!(.bad %in% c("genRxControl"))]
if (length(.bad) > 0) {
stop("unused argument: ", paste
(paste0("'", .bad, "'", sep=""), collapse=", "),
call.=FALSE)
}
checkmate::assertIntegerish(stickyRecalcN, any.missing=FALSE, lower=0, len=1)
checkmate::assertIntegerish(maxOdeRecalc, any.missing=FALSE, len=1)
checkmate::assertNumeric(odeRecalcFactor, len=1, lower=1, any.missing=FALSE)
.genRxControl <- FALSE
if (!is.null(.xtra$genRxControl)) {
.genRxControl <- .xtra$genRxControl
}
if (is.null(ndigit)) {
ndigit <- sigdig
}
if (is.null(rxControl)) {
if (!is.null(sigdig)) {
rxControl <- rxode2::rxControl(sigdig=sigdig)
} else {
rxControl <- rxode2::rxControl(atol=1e-4, rtol=1e-4)
}
.genRxControl <- TRUE
} else if (inherits(rxControl, "rxControl")) {
} else if (is.list(rxControl)) {
rxControl <- do.call(rxode2::rxControl, rxControl)
} else {
stop("solving options 'rxControl' needs to be generated from 'rxode2::rxControl'", call=FALSE)
}
if (!is.null(sigdig)) {
checkmate::assertNumeric(sigdig, lower=1, finite=TRUE, any.missing=TRUE, len=1)
if (is.null(sigdigTable)) {
sigdigTable <- round(sigdig)
}
}
if (is.null(sigdigTable)) {
sigdigTable <- 3
}
checkmate::assertIntegerish(sigdigTable, lower=1, len=1, any.missing=FALSE)
.solveTypeIdx <- c("hessian" = 3L, "grad" = 2L, "fun" = 1L)
if (checkmate::testIntegerish(solveType, len=1, lower=1, upper=6, any.missing=FALSE)) {
solveType <- as.integer(solveType)
} else {
solveType <- setNames(.solveTypeIdx[match.arg(solveType)], NULL)
}
if (missing(covMethod) && any(solveType == 2:3)) {
covMethod <- "nlm"
} else {
covMethod <- match.arg(covMethod)
}
.eventTypeIdx <- c("central" =2L, "forward"=1L)
if (checkmate::testIntegerish(eventType, len=1, lower=1, upper=6, any.missing=FALSE)) {
eventType <- as.integer(eventType)
} else {
eventType <- setNames(.eventTypeIdx[match.arg(eventType)], NULL)
}
.optimHessTypeIdx <- c("central" =2L, "forward"=1L)
if (checkmate::testIntegerish(optimHessType, len=1, lower=1, upper=6, any.missing=FALSE)) {
optimHessType <- as.integer(optimHessType)
} else {
optimHessType <- setNames(.optimHessTypeIdx[match.arg(optimHessType)], NULL)
}
checkmate::assertLogical(useColor, any.missing=FALSE, len=1)
checkmate::assertIntegerish(print, len=1, lower=0, any.missing=FALSE)
checkmate::assertIntegerish(printNcol, len=1, lower=1, any.missing=FALSE)
if (checkmate::testIntegerish(scaleType, len=1, lower=1, upper=4, any.missing=FALSE)) {
scaleType <- as.integer(scaleType)
} else {
.scaleTypeIdx <- c("norm" = 1L, "nlmixr2" = 2L, "mult" = 3L, "multAdd" = 4L)
scaleType <- setNames(.scaleTypeIdx[match.arg(scaleType)], NULL)
}
.normTypeIdx <- c("rescale2" = 1L, "rescale" = 2L, "mean" = 3L, "std" = 4L, "len" = 5L, "constant" = 6L)
if (checkmate::testIntegerish(normType, len=1, lower=1, upper=6, any.missing=FALSE)) {
normType <- as.integer(normType)
} else {
normType <- setNames(.normTypeIdx[match.arg(normType)], NULL)
}
checkmate::assertNumeric(scaleCmax, lower=0, any.missing=FALSE, len=1)
checkmate::assertNumeric(scaleCmin, lower=0, any.missing=FALSE, len=1)
if (!is.null(scaleC)) {
checkmate::assertNumeric(scaleC, lower=0, any.missing=FALSE)
}
checkmate::assertNumeric(scaleTo, len=1, lower=0, any.missing=FALSE)
checkmate::assertNumeric(gradTo, len=1, lower=0, any.missing=FALSE)
.ret <- list(covMethod=covMethod,
typsize = typsize,
fscale = fscale, print.level = print.level, ndigit=ndigit, gradtol = gradtol,
stepmax = stepmax,
steptol = steptol, iterlim = iterlim,
check.analyticals = check.analyticals,
optExpression=optExpression,
literalFix=literalFix,
sumProd=sumProd,
rxControl=rxControl,
returnNlm=returnNlm,
stickyRecalcN=as.integer(stickyRecalcN),
maxOdeRecalc=as.integer(maxOdeRecalc),
odeRecalcFactor=odeRecalcFactor,
eventType=eventType,
shiErr=shiErr,
shi21maxFD=as.integer(shi21maxFD),
optimHessType=optimHessType,
hessErr=hessErr,
shi21maxHess=as.integer(shi21maxHess),
useColor=useColor,
print=print,
printNcol=printNcol,
scaleType=scaleType,
normType=normType,
scaleCmax=scaleCmax,
scaleCmin=scaleCmin,
scaleC=scaleC,
scaleTo=scaleTo,
gradTo=gradTo,
addProp=addProp, calcTables=calcTables,
compress=compress,
solveType=solveType,
ci=ci, sigdig=sigdig, sigdigTable=sigdigTable,
genRxControl=.genRxControl)
class(.ret) <- "nlmControl"
.ret
}
#' Get the nlm family control
#'
#' @param env nlm optimization environment
#' @param ... Other arguments
#' @return Nothing, called for side effects
#' @author Matthew L. Fidler
#' @noRd
.nlmFamilyControl <- function(env, ...) {
.ui <- env$ui
.control <- env$control
if (is.null(.control)) {
.control <- nlmixr2est::nlmControl()
}
if (!inherits(.control, "nlmControl")){
.control <- do.call(nlmixr2est::nlmControl, .control)
}
assign("control", .control, envir=.ui)
}
#' @rdname nmObjHandleControlObject
#' @export
nmObjHandleControlObject.nlmControl <- function(control, env) {
assign("nlmControl", control, envir=env)
}
#' @rdname nmObjGetControl
#' @export
nmObjGetControl.nlm <- function(x, ...) {
.env <- x[[1]]
if (exists("nlmControl", .env)) {
.control <- get("nlmControl", .env)
if (inherits(.control, "nlmControl")) return(.control)
}
if (exists("control", .env)) {
.control <- get("control", .env)
if (inherits(.control, "nlmControl")) return(.control)
}
stop("cannot find nlm related control object", call.=FALSE)
}
#' @rdname getValidNlmixrControl
#' @export
getValidNlmixrCtl.nlm <- function(control) {
.ctl <- control[[1]]
if (is.null(.ctl)) .ctl <- nlmControl()
if (is.null(attr(.ctl, "class")) && is(.ctl, "list")) .ctl <- do.call("nlmControl", .ctl)
if (!inherits(.ctl, "nlmControl")) {
.minfo("invalid control for `est=\"nlm\"`, using default")
.ctl <- nlmControl()
} else {
.ctl <- do.call(nlmControl, .ctl)
}
.ctl
}
.nlmEnv <- new.env(parent=emptyenv())
#' A surrogate function for nlm to call for ode solving
#'
#' @param pars Parameters that will be estimated
#' @return Predictions
#' @details
#' This is an internal function and should not be called directly.
#' @author Matthew L. Fidler
#' @keywords internal
#' @export
.nlmixrNlmFunC <- function(pars) {
.Call(`_nlmixr2est_nlmSolveSwitch`, pars)
}
#' Get the THETA lines from rxode2 UI and assign fixed
#'
#' @param rxui This is the rxode2 ui object
#' @return The theta/eta lines
#' @author Matthew L. Fidler
#' @noRd
.uiGetThetaDropFixed <- function(rxui) {
.iniDf <- rxui$iniDf
.w <- which(!is.na(.iniDf$ntheta))
.env <- new.env(parent=emptyenv())
.env$t <- 0
lapply(.w, function(i) {
if (.iniDf$fix[i]) {
eval(str2lang(paste0("quote(", .iniDf$name[i], " <- ", .iniDf$est[i], ")")))
} else {
.env$t <- .env$t + 1
eval(str2lang(paste0("quote(", .iniDf$name[i], " <- THETA[", .env$t, "])")))
}
})
}
#'@export
rxUiGet.nlmModel0 <- function(x, ...) {
.ui <- rxode2::rxUiDecompress(x[[1]])
assignInMyNamespace(".rxPredLlik", TRUE)
on.exit(assignInMyNamespace(".rxPredLlik", NULL))
.predDf <- .ui$predDf
.save <- .predDf
.predDf[.predDf$distribution == "norm", "distribution"] <- "dnorm"
assign(".predDfFocei", .predDf, envir=.ui)
#assign("predDf", .predDf, envir=.ui)
on.exit(assign("predDf", .save, envir=.ui))
.ret <- rxode2::rxCombineErrorLines(.ui, errLines=rxGetDistributionFoceiLines(.ui),
prefixLines=.uiGetThetaDropFixed(.ui),
paramsLine=NA, #.uiGetThetaEtaParams(.f),
modelVars=TRUE,
cmtLines=FALSE,
dvidLine=FALSE)
as.call(c(list(quote(`rxModelVars`)), as.call(c(list(quote(`{`)),
lapply(seq_along(.ret)[-1], function(i) .ret[[i]]),
list(str2lang("rx_pred_ <- -rx_pred_"))))))
}
#' Load the nlm model into symengine
#'
#' @param x rxode2 UI object
#' @return String for loading into symengine
#' @author Matthew L. Fidler
#' @noRd
.nlmPrune <- function(x) {
.x <- x[[1]]
.x <- .x$nlmModel0[[-1]]
.env <- new.env(parent = emptyenv())
.env$.if <- NULL
.env$.def1 <- NULL
.malert("pruning branches ({.code if}/{.code else}) of population log-likelihood model...")
.ret <- rxode2::.rxPrune(.x, envir = .env)
.mv <- rxode2::rxModelVars(.ret)
## Need to convert to a function
if (rxode2::.rxIsLinCmt() == 1L) {
.vars <- c(.mv$params, .mv$lhs, .mv$slhs)
.mv <- rxode2::.rxLinCmtGen(length(.mv$state), .vars)
}
.msuccess("done")
rxode2::rxNorm(.mv)
}
#' @export
rxUiGet.loadPruneNlm <- function(x, ...) {
.p <- .nlmPrune(x)
.loadSymengine(.p, promoteLinSens = FALSE)
}
#' @export
rxUiGet.nlmParams <- function(x, ...) {
.ui <- x[[1]]
.iniDf <- .ui$iniDf
.w <- which(!.iniDf$fix)
.env <- new.env(parent=emptyenv())
.env$t <- 0
paste0("params(",
paste(c(vapply(.w, function(i) {
.env$t <- .env$t + 1
paste0("THETA[", .env$t, "]")
}, character(1), USE.NAMES = FALSE), "DV"),
collapse=","), ")")
}
#' @export
rxUiGet.nlmRxModel <- function(x, ...) {
.s <- rxUiGet.loadPruneNlm(x, ...)
.prd <- get("rx_pred_", envir = .s)
.prd <- paste0("rx_pred_=", rxode2::rxFromSE(.prd))
## .lhs0 <- .s$..lhs0
## if (is.null(.lhs0)) .lhs0 <- ""
.ddt <- .s$..ddt
if (is.null(.ddt)) .ddt <- ""
.ret <- paste(c(
#.s$..stateInfo["state"],
#.lhs0,
.ddt,
.prd,
#.s$..stateInfo["statef"],
#.s$..stateInfo["dvid"],
""
), collapse = "\n")
if (exists("..maxTheta", .s)) {
.eventTheta <- rep(0L, .s$..maxTheta)
} else {
.eventTheta <- integer(0)
}
for (.v in .s$..eventVars) {
.vars <- as.character(get(.v, envir = .s))
.vars <- rxode2::rxGetModel(paste0("rx_lhs=", rxode2::rxFromSE(.vars)))$params
for (.v2 in .vars) {
.reg <- rex::rex(start, "THETA[", capture(any_numbers), "]", end)
if (regexpr(.reg, .v2) != -1) {
.num <- as.numeric(sub(.reg, "\\1", .v2))
.eventTheta[.num] <- 1L
}
}
}
.s$.eventTheta <- .eventTheta
.sumProd <- rxode2::rxGetControl(x[[1]], "sumProd", FALSE)
.optExpression <- rxode2::rxGetControl(x[[1]], "optExpression", TRUE)
if (.sumProd) {
.malert("stabilizing round off errors in population log-likelihood model...")
.ret <- rxode2::rxSumProdModel(.ret)
.msuccess("done")
}
if (.optExpression) {
.ret <- rxode2::rxOptExpr(.ret, "population log-likelihood model")
.msuccess("done")
}
list(predOnly=rxode2::rxode2(paste(c(rxUiGet.nlmParams(x, ...), rxUiGet.foceiCmtPreModel(x, ...),
.ret, .foceiToCmtLinesAndDvid(x[[1]])), collapse="\n")),
eventTheta=.eventTheta)
}
#' @export
rxUiGet.loadPruneNlmSens <- function(x, ...) {
.loadSymengine(.nlmPrune(x), promoteLinSens = TRUE)
}
#' @export
rxUiGet.nlmThetaS <- function(x, ...) {
.s <- rxUiGet.loadPruneNlmSens(x, ...)
.sensEtaOrTheta(.s, theta=TRUE)
}
#' @export
rxUiGet.nlmHdTheta <- function(x, ...) {
.s <- rxUiGet.nlmThetaS(x)
.stateVars <- rxode2::rxState(.s)
.predMinusDv <- rxode2::rxGetControl(x[[1]], "predMinusDv", TRUE)
.grd <- rxode2::rxExpandFEta_(
.stateVars, .s$..maxTheta,
ifelse(.predMinusDv, 1L, 2L),
isTheta=TRUE)
if (rxode2::.useUtf()) {
.malert("calculate \u2202(f)/\u2202(\u03B8)")
} else {
.malert("calculate d(f)/d(theta)")
}
rxode2::rxProgress(dim(.grd)[1])
on.exit({
rxode2::rxProgressAbort()
})
.any.zero <- FALSE
.all.zero <- TRUE
.ret <- apply(.grd, 1, function(x) {
.l <- x["calc"]
.l <- eval(parse(text = .l))
.ret <- paste0(x["dfe"], "=", rxode2::rxFromSE(.l))
.zErr <- suppressWarnings(try(as.numeric(get(x["dfe"], .s)), silent = TRUE))
if (identical(.zErr, 0)) {
.any.zero <<- TRUE
} else if (.all.zero) {
.all.zero <<- FALSE
}
rxode2::rxTick()
.ret
})
if (.all.zero) {
stop("none of the predictions depend on 'THETA'", call. = FALSE)
}
if (.any.zero) {
warning("some of the predictions do not depend on 'THETA'", call. = FALSE)
}
.s$..HdTheta <- .ret
.s$..pred.minus.dv <- .predMinusDv
rxode2::rxProgressStop()
.s
}
#' Finalize nlm rxode2 based on symengine saved info
#'
#' @param .s Symengine/rxode2 object
#' @return Nothing
#' @author Matthew L Fidler
#' @noRd
.rxFinalizeNlm <- function(.s, sum.prod = FALSE,
optExpression = TRUE) {
.prd <- get("rx_pred_", envir = .s)
.prd <- paste0("rx_pred_=", rxode2::rxFromSE(.prd))
.yj <- paste(get("rx_yj_", envir = .s))
.yj <- paste0("rx_yj_~", rxode2::rxFromSE(.yj))
.lambda <- paste(get("rx_lambda_", envir = .s))
.lambda <- paste0("rx_lambda_~", rxode2::rxFromSE(.lambda))
.hi <- paste(get("rx_hi_", envir = .s))
.hi <- paste0("rx_hi_~", rxode2::rxFromSE(.hi))
.low <- paste(get("rx_low_", envir = .s))
.low <- paste0("rx_low_~", rxode2::rxFromSE(.low))
.ddt <- .s$..ddt
if (is.null(.ddt)) .ddt <- character(0)
.sens <- .s$..sens
if (is.null(.sens)) .sens <- character(0)
.s$..nlmS <- paste(c(
.s$params,
.s$..stateInfo["state"],
.ddt,
.sens,
.yj,
.lambda,
.hi,
.low,
.prd,
.s$..HdTheta,
.s$..stateInfo["statef"],
.s$..stateInfo["dvid"],
""
), collapse = "\n")
.lhs0 <- .s$..lhs0
if (is.null(.lhs0)) .lhs0 <- ""
.s$..pred.nolhs <- paste(c(
.s$params,
.s$..stateInfo["state"],
.lhs0,
.ddt,
.yj,
.lambda,
.hi,
.low,
.prd,
.s$..stateInfo["statef"],
.s$..stateInfo["dvid"],
""
), collapse = "\n")
if (sum.prod) {
.malert("stabilizing round off errors in nlm llik gradient problem...")
.s$..nlmS <- rxode2::rxSumProdModel(.s$..nlmS)
.msuccess("done")
.malert("stabilizing round off errors in nlm llik pred-only problem...")
.s$..pred.nolhs <- rxode2::rxSumProdModel(.s$..pred.nolhs)
.msuccess("done")
}
if (optExpression) {
.s$..nlmS <- rxode2::rxOptExpr(.s$..nlmS, "nlm llik gradient")
.s$..pred.nolhs <- rxode2::rxOptExpr(.s$..pred.nolhs, "nlm pred-only")
}
}
#' @export
rxUiGet.nlmEnv <- function(x, ...) {
.s <- rxUiGet.nlmHdTheta(x, ...)
.s$params <- rxUiGet.nlmParams(x, ...)
.sumProd <- rxode2::rxGetControl(x[[1]], "sumProd", FALSE)
.optExpression <- rxode2::rxGetControl(x[[1]], "optExpression", TRUE)
.rxFinalizeNlm(.s, .sumProd, .optExpression)
.s$..outer <- NULL
if (exists("..maxTheta", .s)) {
.eventTheta <- rep(0L, .s$..maxTheta)
} else {
.eventTheta <- integer(0)
}
for (.v in .s$..eventVars) {
.vars <- as.character(get(.v, envir = .s))
.vars <- rxode2::rxGetModel(paste0("rx_lhs=", rxode2::rxFromSE(.vars)))$params
for (.v2 in .vars) {
.reg <- rex::rex(start, "THETA[", capture(any_numbers), "]", end)
if (regexpr(.reg, .v2) != -1) {
.num <- as.numeric(sub(.reg, "\\1", .v2))
.eventTheta[.num] <- 1L
}
}
}
## if (.sumProd) {
## .malert("stabilizing round off errors in pred-only model...")
## s$..pred.nolhs <- rxode2::rxSumProdModel(.s$..pred.nolhs)
## .msuccess("done")
## }
## if (.optExpression) {
## s$..pred.nolhs <- rxode2::rxOptExpr(.s$..pred.nolhs,
## ifelse(.getRxPredLlikOption(),
## "Llik pred-only model",
## "pred-only model"))
## }
## s$..pred.nolhs <- paste(c(
## paste0("params(", paste(inner$params, collapse = ","), ")"),
## s$..pred.nolhs
## ), collapse = "\n")
.s$.eventTheta <- .eventTheta
.s
}
#attr(rxUiGet.foceEnv, "desc") <- "Get the foce environment"
#' @export
rxUiGet.nlmSensModel <- function(x, ...) {
.s <- rxUiGet.nlmEnv(x, ...)
list(thetaGrad=rxode2::rxode2(.s$..nlmS),
predOnly=rxode2::rxode2(.s$..pred.nolhs),
eventTheta=.s$.eventTheta)
}
#' @export
rxUiGet.nlmParNameFun <- function(x, ...) {
.ui <- x[[1]]
.iniDf <- .ui$iniDf
.env <- new.env(parent=emptyenv())
.env$i <- 1
.w <- which(!.iniDf$fix)
eval(str2lang(
paste0("function(p) {c(",
paste(vapply(.w, function(t) {
.ret <- paste0("'THETA[", .env$i, "]'=p[", .env$i, "]")
.env$i <- .env$i + 1
.ret
}, character(1), USE.NAMES=FALSE), collapse=","), ")}")))
}
#' @export
rxUiGet.optimParNameFun <- rxUiGet.nlmParNameFun
#' @export
rxUiGet.nlmParIni <- function(x, ...) {
.ui <- x[[1]]
.ui$iniDf$est[!.ui$iniDf$fix]
}
#' @export
rxUiGet.optimParIni <- rxUiGet.nlmParIni
#' @export
rxUiGet.nlmParName <- function(x, ...) {
.ui <- x[[1]]
.ui$iniDf$name[!.ui$iniDf$fix]
}
#' @export
rxUiGet.optimParName <- rxUiGet.nlmParName
#' Setup the data for nlm estimation
#'
#' @param dataSav Formatted Data
#' @return Nothing, called for side effects
#' @author Matthew L. Fidler
#' @noRd
.nlmFitDataSetup <- function(dataSav) {
.dsAll <- dataSav[dataSav$EVID != 2, ] # Drop EVID=2 for estimation
if (any(names(.dsAll) == "CENS")) {
if (!all(.dsAll$CENS == 0)) {
stop("'nlm' does not work with censored data", call. =FALSE)
}
}
.nlmEnv$data <- rxode2::etTrans(.dsAll, .nlmEnv$model)
}
.nlmFitModel <- function(ui, dataSav) {
.ctl <- ui$control
class(.ctl) <- NULL
.p <- setNames(ui$nlmParIni, ui$nlmParName)
.typsize <- .ctl$typsize
if (is.null(.typsize)) {
.typsize <- rep(1, length(.p))
} else if (length(.typsize) == 1L) {
.typsize <- rep(.typsize, length(.p))
} else {
stop("'typsize' needs to match the number of estimated parameters (or equal 1)", call.=FALSE)
}
.stepmax <- .ctl$stepmax
if (is.null(.stepmax)) {
.stepmax <- max(1000 * sqrt(sum((.p/.typsize)^2)), 1000)
}
.hessian <- .ctl$covMethod == "nlm"
if (.ctl$solveType == 1L) {
.mi <- ui$nlmRxModel
} else {
.mi <- ui$nlmSensModel
}
.env <- .nlmSetupEnv(.p, ui, dataSav, .mi, .ctl)
on.exit({.nlmFreeEnv()})
.ret <- eval(bquote(stats::nlm(
f=.(.nlmixrNlmFunC),
p=.(.env$par.ini),
hessian=.(.hessian),
typsize=.(.typsize),
fscale=.(.ctl$fscale),
print.level=.(.ctl$print.level),
ndigit=.(.ctl$ndigit),
gradtol=.(.ctl$gradtol),
stepmax=.(.stepmax),
steptol = .(.ctl$steptol),
iterlim = .(.ctl$iterlim),
check.analyticals = .(.ctl$check.analyticals)
)))
.nlmFinalizeList(.env, .ret, par="estimate", printLine=TRUE,
hessianCov=TRUE)
}
#' Get the full theta for nlm methods
#'
#' @param nlm enhanced nlm return
#' @param ui ui object
#' @return named theta matrix
#' @author Matthew L. Fidler
#' @noRd
.nlmGetTheta <- function(nlm, ui) {
.iniDf <- ui$iniDf
setNames(vapply(seq_along(.iniDf$name),
function(i) {
if (.iniDf$fix[i]) {
.iniDf$est[i]
} else {
nlm$estimate[.iniDf$name[i]]
}
}, double(1), USE.NAMES=FALSE),
.iniDf$name)
}
.nlmControlToFoceiControl <- function(env, assign=TRUE) {
.nlmControl <- env$nlmControl
.ui <- env$ui
.foceiControl <- foceiControl(rxControl=env$nlmControl$rxControl,
maxOuterIterations=0L,
maxInnerIterations=0L,
covMethod=0L,
sumProd=.nlmControl$sumProd,
optExpression=.nlmControl$optExpression,
literalFix=.nlmControl$literalFix,
scaleTo=0,
calcTables=.nlmControl$calcTables,
addProp=.nlmControl$addProp,
#skipCov=.ui$foceiSkipCov,
interaction=0L,
compress=.nlmControl$compress,
ci=.nlmControl$ci,
sigdigTable=.nlmControl$sigdigTable)
if (assign) env$control <- .foceiControl
.foceiControl
}
.nlmFamilyFit <- function(env, ...) {
.ui <- env$ui
.control <- .ui$control
.data <- env$data
.ret <- new.env(parent=emptyenv())
# The environment needs:
# - table for table options
# - $origData -- Original Data
# - $dataSav -- Processed data from .foceiPreProcessData
# - $idLvl -- Level information for ID factor added
# - $covLvl -- Level information for items to convert to factor
# - $ui for ui fullTheta Full theta information
# - $etaObf data frame with ID, etas and OBJI
# - $cov For covariance
# - $covMethod for the method of calculating the covariance
# - $adjObf Should the objective function value be adjusted
# - $objective objective function value
# - $extra Extra print information
# - $method Estimation method (for printing)
# - $omega Omega matrix
# - $theta Is a theta data frame
# - $model a list of model information for table generation. Needs a `predOnly` model
# - $message Message for display
# - $est estimation method
# - $ofvType (optional) tells the type of ofv is currently being used
# When running the focei problem to create the nlmixr object, you also need a
# foceiControl object
.ret$table <- env$table
.foceiPreProcessData(.data, .ret, .ui, .control$rxControl)
.nlm <- .collectWarn(.nlmFitModel(.ui, .ret$dataSav), lst = TRUE)
.ret$nlm <- .nlm[[1]]
.ret$parHistData <- .ret$nlm$parHistData
.ret$nlm$parHistData <- NULL
.ret$message <- NULL
lapply(.nlm[[2]], function(x){
warning(x, call.=FALSE)
})
if (rxode2::rxGetControl(.ui, "returnNlm", FALSE)) {
return(.ret$nlm)
}
if (.ret$nlm$code == 1) {
.ret$message <- "relative gradient is close to zero, current iterate is probably solution"
} else if (.ret$nlm$code == 2) {
.ret$message <- "successive iterates within tolerance, current iterate is probably solution"
} else if (.ret$nlm$code == 3) {
.ret$message <- c("last global step failed to locate a point lower than 'estimate'",
"either 'estimate' is an approximate local minimum of the function or 'steptol' is too small")
} else if (.ret$nlm$code == 4) {
.ret$message <- "iteration limit exceeded"
} else if (.ret$nlm$code == 5) {
.ret$message <- c("maximum step size 'stepmax' exceeded five consecutive times",
"either the function is unbounded below, becomes asymptotic to a finite value from above in some direction or 'stepmax' is too small")
} else {
.ret$message <- ""
}
.ret$ui <- .ui
.ret$adjObf <- rxode2::rxGetControl(.ui, "adjObf", TRUE)
.ret$fullTheta <- .nlmGetTheta(.ret$nlm, .ui)
.ret$cov <- .ret$nlm$cov
.ret$covMethod <- .ret$nlm$covMethod
#.ret$etaMat <- NULL
#.ret$etaObf <- NULL
#.ret$omega <- NULL
.ret$control <- .control
.ret$extra <- ""
.nlmixr2FitUpdateParams(.ret)
nmObjHandleControlObject(.ret$control, .ret)
if (exists("control", .ui)) {
rm(list="control", envir=.ui)
}
.ret$est <- "nlm"
# There is no parameter history for nlme
.ret$objective <- 2 * as.numeric(.ret$nlm$minimum)
.ret$model <- .ui$ebe
.ret$ofvType <- "nlm"
.nlmControlToFoceiControl(.ret)
.ret$theta <- .ret$ui$saemThetaDataFrame
.ret <- nlmixr2CreateOutputFromUi(.ret$ui, data=.ret$origData, control=.ret$control, table=.ret$table, env=.ret, est="nlm")
.env <- .ret$env
.env$method <- "nlm"
.ret
}
#' @rdname nlmixr2Est
#' @export
nlmixr2Est.nlm <- function(env, ...) {
.ui <- env$ui
rxode2::assertRxUiPopulationOnly(.ui, " for the estimation routine 'nlm', try 'focei'", .var.name=.ui$modelName)
rxode2::assertRxUiRandomOnIdOnly(.ui, " for the estimation routine 'nlm'", .var.name=.ui$modelName)
.nlmFamilyControl(env, ...)
on.exit({if (exists("control", envir=.ui)) rm("control", envir=.ui)}, add=TRUE)
.nlmFamilyFit(env, ...)
}