/
dynmodel.R
1817 lines (1667 loc) · 58.7 KB
/
dynmodel.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
thresh <- function(x, cut = .Machine$double.xmin) {
x <- abs(x)
ifelse(x > cut, x, cut)
}
err.msg <- function(x, pre = "", post = "") {
msg <- paste0(x, collapse = ", ")
paste0(pre, msg, post)
}
##' Convert fit to classic dynmodel object
##'
##' @param x nlmixr object to convert to dynmodel object
##' @return dynmodel
##' @author Matthew Fidler
##' @export
as.dynmodel <- function(x) {
.ret <- try(x$dynmodelObject, silent = TRUE)
if (inherits(.ret, "try-error") || is.null(.ret)) {
stop("Cannot convert to dynmodel object")
}
return(.ret)
}
# plot.dyn.ID() -----------------------------------------------------------
#' Plot of a non-population dynamic model fit
#'
#' @param x a dynamodel fit object
#' @param ... additional arguments
#' @return nothing, displays a goodness of fit plot for dynmodely
#' @export
gof <- function(x, ...) {
gof_str <- "
{
theta = th[1:npar]
names(theta) = names(inits)[1:npar]
theta = c(theta, fixPars)
system$solve(theta, ev, atol = 1e-08, rtol = 1e-08)
}
"
f <- x$obj
dat <- x$data
body(f) <- parse(text = gof_str)
x <- f(x$par)
rows <- environment(f)$rows
m <- environment(f)$model
for (s in m) {
time <- x[, "time"]
yo <- dat[, s["dv"]] # FIXME
yp <- x[, s["pred"]]
# dv vs pred
plot(time, yp, type = "n", xlab = "time", ylab = s["dv"])
points(dat[, "time"], yo, ...)
lines(time, yp)
# pred vs res
yp <- yp[rows]
res <- yo - yp
plot(yp, yp, xlab = "pred", ylab = s["dv"], ...)
abline(0, 1, col = "red", lty = 2)
# pred vs res
plot(yp, res, xlab = "pred", ylab = "res", ...)
abline(h = 0, col = "red", lty = 2)
}
}
#' @export
#' @rdname gof
plot.dyn.ID <- gof
# #########################################################################
# print.dyn.ID() ----------------------------------------------------------
#' Print a non-population dynamic model fit object
#'
#' @param x a dynmodel fit object
#' @param ... additional arguments
#' @return the original object
#' @export
print.dyn.ID <- function(x, ...) {
print(x$res[, c(1, 3)])
cat("\n")
aic <- 2 * x$value + 2 * x$npar
bic <- 2 * x$value + log(x$nobs) * x$npar
print(c("-loglik" = x$value, "AIC" = aic, "BIC" = bic))
cat("\n")
invisible(x)
}
# #########################################################################
# summary.dyn.ID() --------------------------------------------------------
#' Summary of a non-population dynamic model fit
#'
#' @param object a dynmodel fit object
#' @param ... additional arguments
#' @return original object (invisible)
#' @export
summary.dyn.ID <- function(object, ...) {
print(object$res)
cat("\n")
aic <- 2 * object$value + 2 * object$npar
bic <- 2 * object$value + log(object$nobs) * object$npar
print(c("-loglik" = object$value, "AIC" = aic, "BIC" = bic))
cat("\niter:", object$iter, "\n")
cat(object$message, "\n")
invisible(object)
}
# nmsimplex() and mymin() -------------------------------------------------
#' Nelder-Mead simplex search
#'
#' @param start initials
#' @param fr objective function
#' @param rho evaluation environment
#' @param control additional optimization options
#' @return a list of ...
#' @export
nmsimplex <- function(start, fr, rho = NULL, control = list()) {
if (is.null(rho)) rho <- environment(fr)
step <- -.2 * start
con <- list(maxeval = 999, reltol = 1e-6, rcoeff = 1., ecoeff = 2., ccoeff = .5, trace = FALSE)
nmsC <- names(con)
con[(namc <- names(control))] <- control
if (length(noNms <- namc[!namc %in% nmsC])) {
warning("unknown names in control: ", paste(noNms, collapse = ", "))
}
.Call(neldermead_wrap, fr, rho, length(start), start, step,
as.integer(con$maxeval), con$reltol, con$rcoeff, con$ecoeff, con$ccoeff,
as.integer(con$trace),
PACKAGE = "nlmixr"
)
}
mymin <- function(start, fr, rho = NULL, control = list()) {
if (is.null(rho)) rho <- environment(fr)
step <- -.2 * start
con <- list(maxeval = 999, reltol = 1e-6, rcoeff = 1., ecoeff = 2., ccoeff = .5, trace = FALSE)
nmsC <- names(con)
con[(namc <- names(control))] <- control
# if (length(noNms <- namc[!namc %in% nmsC]))
# warning("unknown names in control: ", paste(noNms, collapse = ", "))
.Call(neldermead_wrap, fr, rho, length(start), start, step,
as.integer(con$maxeval), con$reltol, con$rcoeff, con$ecoeff, con$ccoeff,
as.integer(con$trace),
PACKAGE = "nlmixr"
)
}
# #########################################################################
# as.focei.dynmodel() -----------------------------------------------------------
#' Output nlmixr format for dynmodel
#'
#' Convert dynmodel output to nlmixr focei style output
#'
#' @param .dynmodelObject dynmodel object
#' @param .nlmixrObject nlmixr object
#' @param .data RxODE data set
#' @param .time proc.time object used in dynmodel timing
#' @param .theta estimated terms excluding error terms
#' @param .fit optimized parameters
#' @param .message optimization messages
#' @param .inits.err initial estimates for error terms
#' @param .cov covariance matrix from solved Hessian
#' @param .sgy variance of Y given the model
#' @param .dynmodelControl control options for dynmodel
#' @param .nobs2 -
#' @param .pt proc.time object used in dynmodel timing
#' @param .rxControl control options for RxODE
#' @return A UI version of a dynmodel object
#' @author Mason McComb and Matt Fidler
#' @keywords internal
#' @export
as.focei.dynmodel <- function(.dynmodelObject, .nlmixrObject, .data,
.time, .theta, .fit, .message, .inits.err,
.cov, .sgy, .dynmodelControl, .nobs2 = 0,
.pt = proc.time(),
.rxControl = RxODE::rxControl()) {
.Estimates <- .dynmodelObject$res[, 1]
.model <- RxODE::rxSymPySetupPred(.nlmixrObject$rxode.pred,
function() {
return(nlmixr_pred)
},
.nlmixrObject$theta.pars,
.nlmixrObject$error,
grad = FALSE,
pred.minus.dv = TRUE, sum.prod = FALSE, # control$sumProd,
theta.derivs = FALSE, optExpression = TRUE, # control$optExpression,
run.internal = TRUE, only.numeric = TRUE
)
.temp.model <- .model
.nlmixrObject.df <- as.data.frame(.nlmixrObject$ini)
# assign fixed terms
.fix.index <-
if (length(which(.nlmixrObject.df$fix == TRUE)) == 0) {
NULL
} else {
which(.nlmixrObject.df$fix == TRUE)
} # obtain row location for fixed terms
.ref.fix <- substring(.nlmixrObject.df$name[.fix.index], 2)
.temp.log.fixPars.index <- intersect(.fix.index, .temp.model$log.etas)
.temp.log.fixPars <- .nlmixrObject.df$est[.temp.log.fixPars.index]
names(.temp.log.fixPars) <- substring(.nlmixrObject.df$name[.temp.log.fixPars.index], 2)
.temp.nonlog.fixPars.index <- setdiff(.fix.index, .temp.model$log.etas)
.temp.nonlog.fixPars <- .nlmixrObject.df$est[.temp.nonlog.fixPars.index]
names(.temp.nonlog.fixPars) <- substring(.nlmixrObject.df$name[.temp.nonlog.fixPars.index], 2)
.fixPars <- c(.temp.log.fixPars, .temp.nonlog.fixPars)
.fixPars <- .fixPars[order(factor(names(.fixPars), levels = .ref.fix))]
# assign theta terms(estimated terms excluding error terms)
.theta.index <-
if (is.null(.fix.index)) {
which(!is.na(.nlmixrObject.df$ntheta) & is.na(.nlmixrObject.df$err), TRUE)
} else {
which(!is.na(.nlmixrObject.df$ntheta) & is.na(.nlmixrObject.df$err), TRUE)[-which(.nlmixrObject.df$fix == TRUE)]
}
## $nlmixrObject ----
.temp.theta.index <-
c(1:sum(
as.data.frame(
.nlmixrObject$ini
)$fix == FALSE &
is.na(as.data.frame(.nlmixrObject$ini)$err)
))
.temp.replacements <- .dynmodelObject$res[.theta.index, 1]
ini <- as.data.frame(.nlmixrObject$ini)
ini$est[.temp.theta.index] <- c(.temp.replacements)
class(ini) <- c("nlmixrBounds", "data.frame")
.nlmixrObject$ini <- ini
uif <- .nlmixrObject
## now use focei to get the same estimates
.env <- new.env(parent = emptyenv())
## put in covariance information
labels <- names(.Estimates)
dimnames(.cov) <- list(labels, labels)
.env$cov <- .cov
.env$nobs <- .dynmodelObject$nobs
.env$covMethod <- .dynmodelControl$covMethod
.ctl <- .dynmodelControl
class(.ctl) <- NULL
.ctl$maxOuterIterations <- 0
.ctl$maxInnerIterations <- 0
.ctl$covMethod <- ""
.ctl$sumProd <- uif$env$sum.prod
.ctl$optExpression <- uif$env$optExpression
.ctl$scaleTo <- 0
.ctl$calcTables
.ctl$method <- "liblsoda"
.ctl <- do.call(foceiControl, .ctl)
if (.ctl$singleOde) {
.mod <- uif$focei.rx1
.pars <- NULL
} else {
.mod <- uif$rxode.pred
.pars <- uif$theta.pars
}
fit.f <- try(foceiFit.data.frame(
data = .data, inits = uif$focei.inits, PKpars = .pars,
model = .mod, pred = function() {
return(nlmixr_pred)
}, err = uif$error,
lower = uif$focei.lower,
upper = uif$focei.upper,
thetaNames = uif$focei.names,
etaNames = uif$eta.names,
fixed = uif$focei.fixed,
env = .env,
control = .ctl
), silent = FALSE)
assign("method", "dynmodel", .env)
assign("extra", sprintf("(method: %s)", .dynmodelControl$method), .env)
assign("dynmodelObject", .dynmodelObject, .env)
.cls <- c("nlmixrDynmodel", class(fit.f))
attr(.cls, ".foceiEnv") <- .env
class(fit.f) <- .cls
return(fit.f)
}
# nlmixrDynmodelConvert() #################################################
#' Converting nlmixr objects to dynmodel objects
#'
#' Convert nlmixr Objects to dynmodel objects for use in fitting non-population dynamic models
#'
#' @param .nmf nlmixr object
#' @return list containing inputs for the dynmodel()
#' \itemize{
#' \item \code{$fixPars} - fixed parameters defined as \code{fixed()} in the nlmixr object
#' \item \code{$sigma} - error model parameters
#' \item \code{$inits} - initial estimates for parameters in the model
#' \item \code{$lower} - lower boundaries for estimated parameters
#' \item \code{$upper} - upper boundaries for estimated parameters
#' \item \code{$system} - RxODE object that defines the structural model
#' \item \code{$model} - error model
#' }
#'
#' @author Mason McComb and Matt Fidler
#' @export
nlmixrDynmodelConvert <- function(.nmf) {
# initialize list for output
.return <- list()
# convert nlmixr model to data.frame
.nmf.original <- .nmf
.nmf <- as.data.frame(.nmf$ini)
.temp.model <-
RxODE::rxSymPySetupPred(
.nmf.original$rxode.pred,
function() {
return(nlmixr_pred)
},
.nmf.original$theta.pars,
.nmf.original$error,
grad = FALSE,
pred.minus.dv = TRUE,
sum.prod = FALSE, # control$sumProd,
theta.derivs = FALSE,
optExpression = TRUE, # control$optExpression,
run.internal = TRUE,
only.numeric = TRUE
)
# assign fixed terms
.fix.index <- # obtain row location for fixed terms
if (length(which(.nmf$fix == TRUE)) == 0) {
NULL
} else {
which(.nmf$fix == TRUE)
}
.ref.fix <- substring(.nmf$name[.fix.index], 2)
.temp.log.fixPars.index <- intersect(.fix.index, .temp.model$log.etas)
.temp.log.fixPars <- .nmf$est[.temp.log.fixPars.index]
names(.temp.log.fixPars) <- substring(.nmf$name[.temp.log.fixPars.index], 2)
.temp.nonlog.fixPars.index <- setdiff(.fix.index, .temp.model$log.etas)
.temp.nonlog.fixPars <- .nmf$est[.temp.nonlog.fixPars.index]
names(.temp.nonlog.fixPars) <- substring(.nmf$name[.temp.nonlog.fixPars.index], 2)
.fixPars <- c(.temp.log.fixPars, .temp.nonlog.fixPars)
.fixPars <- .fixPars[order(factor(names(.fixPars), levels = .ref.fix))]
.return <- c(.return, fixPars = list(.fixPars))
# assign theta terms(estimated terms excluding error terms)
.theta.index <-
if (is.null(.fix.index)) {
which(!is.na(.nmf$ntheta) & is.na(.nmf$err), TRUE)
} else {
which(!is.na(.nmf$ntheta) & is.na(.nmf$err), TRUE)[-which(.nmf$fix == TRUE)]
} # row location for theta values
.ref.theta <- .nmf$name[.theta.index]
.temp.log.theta.index <- intersect(.theta.index, .temp.model$log.etas)
.temp.log.theta <- .nmf$est[.temp.log.theta.index]
names(.temp.log.theta) <- .nmf$name[.temp.log.theta.index]
.temp.nonlog.theta.index <- setdiff(.theta.index, .temp.model$log.etas)
.temp.nonlog.theta <- .nmf$est[.temp.nonlog.theta.index]
names(.temp.nonlog.theta) <- .nmf$name[.temp.nonlog.theta.index]
.theta <- c(.temp.nonlog.theta, .temp.log.theta)
.theta <- .theta[order(factor(names(.theta), levels = .ref.theta))]
# .theta.name.index <- .theta.index + 2 + length(.theta.index) + length(.fix.index)
# names(.theta) <- .temp.model$pred.only$lhs[.theta.name.index]
# assign sigma terms (estimated)
.sigma.index <-
if (is.null(.fix.index)) {
which(!is.na(.nmf$ntheta) & !is.na(.nmf$err), TRUE)
} else {
which(!is.na(.nmf$ntheta) & !is.na(.nmf$err), TRUE)[-which(.nmf$fix == TRUE)]
} # row location for theta values
.sigma <- .nmf$est[.sigma.index] # initial estimate for theta values, back-transformed
names(.sigma) <- .nmf$err[.sigma.index]
.return <- c(.return, sigma = list(.sigma))
# assign "inits", vector of theta and sigma terms # (will be used when the likelihood function is changed)
.inits <- .theta
.return$inits <- .inits
# assign boundaries
mask_theta_term <- !is.na(.nmf$ntheta) & !.nmf$fix & is.na(.nmf$err)
mask_error_term <- !is.na(.nmf$ntheta) & !.nmf$fix & !is.na(.nmf$err)
.lower <-
c(
.nmf$lower[mask_theta_term], # theta terms
.nmf$lower[mask_error_term] # error terms
)
.upper <-
c(
.nmf$upper[mask_theta_term], # theta terms
.nmf$upper[mask_error_term] # error terms
)
.return <- c(.return, lower = list(.lower), upper = list(.upper))
# obtain system
.system <- RxODE(.nmf.original$rxode.pred) # (use nlmixr_pred)
.system$stateExtra <- NULL # remove extraState, the error model term should not be inclcuded
.system$lhs <- .system$lhs[-length(.system$lhs)] # remove the error model term
.return <- c(.return, system = .system)
# create error model
.DV <- .nmf$condition[!is.na(.nmf$condition) & .nmf$condition != "ID"]
.PRED <- "nlmixr_pred" # need to obtain from data? id dont know
.formula <- list()
for (i in 1:length(.sigma.index)) {
if (i == 1) {
.temp <- paste(.nmf$err[.sigma.index[i]], "(", .nmf$est[.sigma.index[i]], ")", sep = "")
} else {
.temp <- paste("+ ", .nmf$err[.sigma.index[i]], "(", .nmf$est[.sigma.index[i]], ")", sep = "")
}
.formula <- paste(.formula, .temp)
}
.model <- as.formula(paste(.DV, "~", .PRED, "+", .formula))
.return <- c(.return, model = .model)
# Output
return(.return)
}
# dynmodelControl() #######################################################
#' Control Options for dynmodel
#'
#' @inheritParams RxODE::rxSolve
#' @inheritParams foceiControl
#'
#' @param nlmixrOutput Option to change output style to nlmixr output. By default
#' this is FALSE.
#' @param digs Option for the number of significant digits of the output. By
#' default this is 3.
#' @param lower Lower bounds on the parameters used in optimization. By default
#' this is -Inf.
#' @param upper Upper bounds on the parameters used in optimization. By default
#' this is Inf.
#' @param maxeval Maximum number of iterations for Nelder-Mead of simplex
#' search. By default this is 999.
#' @param maxit Maximum number of iterations for lbfgsb3c. See
#' \code{\link[lbfgsb3c]{lbfgsb3c}} for more details. By default this is
#' 100000L.
#' @param maxfun The maximum allowed number of function evaluations. If this is
#' exceeded, the method will terminate. See \code{\link[minqa]{bobyqa}} for
#' more details. By default this value is NULL.
#' @param iprint Print option for optimization. See \code{\link[minqa]{bobyqa}},
#' \code{\link[lbfgsb3c]{lbfgsb3c}}, and \code{\link[lbfgs]{lbfgs}} for more
#' details. By default this is 0.
#' @param trace Tracing information on the progress of the optimization is
#' produced. See \code{\link[minqa]{bobyqa}},
#' \code{\link[lbfgsb3c]{lbfgsb3c}}, and \code{\link[lbfgs]{lbfgs}} for more
#' details. By default this is 0.
#' @param factr Controls the convergence of the "L-BFGS-B" method. Convergence
#' occurs when the reduction in the objective is within this factor of the
#' machine tolerance. Default is 1e10, which gives a tolerance of about
#' \code{2e-6}, approximately 4 sigdigs. You can check your exact tolerance
#' by multiplying this value by \code{.Machine$double.eps}
#' @param pgtol is a double precision variable.
#'
#' On entry pgtol >= 0 is specified by the user. The iteration
#' will stop when:
#'
#' \code{max(\| proj g_i \| i = 1, ..., n) <= lbfgsPgtol}
#'
#' where pg_i is the ith component of the projected gradient.
#'
#' On exit pgtol is unchanged. This defaults to zero, when the
#' check is suppressed.
#' @param lmm An integer giving the number of BFGS updates retained in the
#' "L-BFGS-B" method, It defaults to 7.
#' @param abs.tol Used in Nelder-Mead optimization and PORT optimization.
#' Absolute tolerance. Defaults to 0 so the absolute convergence test is not
#' used. If the objective function is known to be non-negative, the previous
#' default of 1e-20 would be more appropriate.
#' @param xf.tol Used in Nelder-Mead optimization and PORT optimization. false
#' convergence tolerance. Defaults to 2.2e-14. See \code{\link[stats]{nlminb}}
#' for more details.
#' @param step.min Used in Nelder-Mead optimization and PORT optimization.
#' Minimum step size. By default this is 1. See \code{\link[stats]{nlminb}}
#' for more details.
#' @param step.max Used in Nelder-Mead optimization and PORT optimization.
#' Maximum step size. By default this is 1. See \code{\link[stats]{nlminb}}
#' for more details.
#' @param sing.tol Used in Nelder-Mead optimization and PORT optimization.
#' Singular convergence tolerance; defaults to rel.tol. See
#' \code{\link[stats]{nlminb}} for more details.
#' @param scale.init Used in Nelder-Mead optimization and PORT optimization.
#' See \code{\link[stats]{nlminb}} for more details.
#' @param diff.g Used in Nelder-Mead optimization and PORT optimization. An
#' estimated bound on the relative error in the objective function value. See
#' \code{\link[stats]{nlminb}} for more details.
#' @param covMethod Method for calculating covariance. In this discussion, R is
#' the Hessian matrix of the objective function. The S matrix is the sum of
#' individual gradient cross-product (evaluated at the individual empirical
#' Bayes estimates).
#' @param rxControl This uses RxODE family of objects, file, or model
#' specification to solve a ODE system. See \code{\link[RxODE]{rxControl}} for
#' more details. By default this is NULL.
#'
#' @inheritParams RxODE::rxSolve
#'
#' @return dynmodelControl list for options during dynmodel optimization
#'
#' @author Mason McComb and Matthew L. Fidler
#' @export
dynmodelControl <- function(...,
ci = 0.95,
nlmixrOutput = FALSE,
digs = 3,
lower = -Inf,
upper = Inf,
## mma doesn't work
## lbfgsbLG
## slsqp
method = c(
"bobyqa", "Nelder-Mead", "lbfgsb3c", "L-BFGS-B", "PORT",
"mma", "lbfgsbLG", "slsqp", "Rvmmin"
),
maxeval = 999,
scaleTo = 1.0,
scaleObjective = 0,
normType = c("rescale2", "constant", "mean", "rescale", "std", "len"),
scaleType = c("nlmixr", "norm", "mult", "multAdd"),
scaleCmax = 1e5,
scaleCmin = 1e-5,
scaleC = NULL,
scaleC0 = 1e5,
# RxODE
atol = NULL,
rtol = NULL,
ssAtol = NULL,
ssRtol = NULL,
# bobyqaControl
npt = NULL,
rhobeg = 0.2,
rhoend = NULL,
iprint = 0,
print = 1,
maxfun = NULL,
# lbfgsb3c
trace = 0,
factr = NULL,
pgtol = NULL,
abstol = NULL,
reltol = NULL,
lmm = NULL,
maxit = 100000L,
# ,iprint=NULL repreated above
# nlminb (PORT)
eval.max = NULL,
iter.max = NULL,
# trace=NULL,
abs.tol = NULL,
rel.tol = NULL,
x.tol = NULL,
xf.tol = NULL,
step.min = NULL,
step.max = NULL,
sing.tol = NULL,
scale.init = NULL,
diff.g = NULL,
## Sigdig
boundTol = NULL,
epsilon = NULL,
derivSwitchTol = NULL,
sigdig = 4,
covMethod = c("nlmixrHess", "optimHess"),
# rxControl
gillK = 10L,
gillStep = 4,
gillFtol = 0,
gillRtol = sqrt(.Machine$double.eps),
gillKcov = 10L,
gillStepCov = 2,
gillFtolCov = 0,
rxControl = NULL) {
if (is.null(boundTol)) {
boundTol <- 5 * 10^(-sigdig + 1)
}
if (is.null(epsilon)) {
epsilon <- 10^(-sigdig - 1)
}
if (is.null(abstol)) {
abstol <- 10^(-sigdig - 1)
}
if (is.null(reltol)) {
reltol <- 10^(-sigdig - 1)
}
if (is.null(rhoend)) {
rhoend <- 10^(-sigdig - 1)
}
if (is.null(factr)) {
factr <- 10^(-sigdig - 1) / .Machine$double.eps
}
if (is.null(atol)) {
atol <- 0.5 * 10^(-sigdig - 2)
}
if (is.null(rtol)) {
rtol <- 0.5 * 10^(-sigdig - 2)
}
if (is.null(ssAtol)) {
ssAtol <- 0.5 * 10^(-sigdig - 1.5)
}
if (is.null(ssRtol)) {
ssRtol <- 0.5 * 10^(-sigdig - 1.5)
}
if (is.null(rel.tol)) {
rel.tol <- 10^(-sigdig - 1)
}
if (is.null(x.tol)) {
x.tol <- 10^(-sigdig - 1)
}
if (is.null(derivSwitchTol)) {
derivSwitchTol <- 2 * 10^(-sigdig - 1)
}
if (inherits(rxControl, "list")) {
if (!any(names(rxControl) == "atol")) {
rxControl$atol <- 0.5 * 10^(-sigdig - 2)
}
if (!any(names(rxControl) == "rtol")) {
rxControl$rtol <- 0.5 * 10^(-sigdig - 2)
}
if (!any(names(rxControl) == "ssAtol")) {
rxControl$ssAtol <- 0.5 * 10^(-sigdig - 1.5)
}
if (!any(names(rxControl) == "ssRtol")) {
rxControl$ssRtol <- 0.5 * 10^(-sigdig - 1.5)
}
rxControl <- do.call(RxODE::rxControl, rxControl)
} else {
atol <- 0.5 * 10^(-sigdig - 2)
rtol <- 0.5 * 10^(-sigdig - 2)
ssAtol <- 0.5 * 10^(-sigdig - 1.5)
ssRtol <- 0.5 * 10^(-sigdig - 1.5)
rxControl <- RxODE::rxControl(atol = atol, rtol = rtol, ssAtol = ssAtol, ssRtol = ssRtol)
}
if (missing(method)) {
method <- "bobyqa"
}
if (missing(normType)) {
normType <- "rescale2"
} # normType= 'constant'
if (missing(scaleType)) {
scaleType <- "nlmixr"
} # scaleType= 'norm'
.ret <- list(
ci = ci,
nlmixrOutput = nlmixrOutput,
digs = digs,
lower = lower,
upper = upper,
method = method,
maxeval = maxeval,
scaleTo = scaleTo,
scaleObjective = scaleObjective,
normType = normType,
scaleType = scaleType,
scaleCmax = scaleCmax,
scaleCmin = scaleCmin,
scaleC = scaleC, # NULL,
scaleC0 = scaleC0,
# RxODE
atol = atol,
rtol = rtol,
# bobyqa
npt = npt,
rhobeg = rhobeg,
rhoend = rhoend,
iprint = iprint, # also used in lbfgsb3c
print = print,
maxfun = maxfun,
# lbfgsb3c
trace = trace,
factr = factr,
pgtol = pgtol,
abstol = abstol,
reltol = reltol,
lmm = lmm,
maxit = maxit,
# ,iprint = iprint,
# nlminb (PORT)
eval.max = eval.max,
iter.max = iter.max,
# trace=NULL,
abs.tol = abs.tol,
rel.tol = rel.tol,
x.tol = x.tol,
xf.tol = xf.tol,
step.min = step.min,
step.max = step.max,
sing.tol = sing.tol,
scale.init = scale.init,
diff.g = diff.g,
covMethod = match.arg(covMethod),
rxControl = rxControl,
gillK = as.integer(gillK),
gillKcov = as.integer(gillKcov),
gillRtol = as.double(gillRtol),
gillStep = as.double(gillStep),
gillStepCov = as.double(gillStepCov),
gillFtol = as.double(gillFtol),
gillFtolCov = as.double(gillFtolCov)
)
.w <- which(sapply(.ret, is.null))
.ret <- .ret[-.w]
class(.ret) <- "dynmodelControl"
return(.ret)
}
# dynmodel() #############################################################
#' Fit a non-population dynamic model
#'
#' @param system RxODE object. See \code{\link[RxODE]{RxODE}} for more details.
#' @param model Error model.
#' @param inits Initial values of system parameters.
#' @param data Dataset to estimate. Needs to be RxODE compatible in EVIDs.
#' @param fixPars Fixed system parameters. Default is NULL.
#' @param nlmixrObject nlmixr object. See \code{\link[nlmixr]{nlmixr}} for more
#' details. Default is NULL.
#' @param control Control options for dynmodel
#' \code{\link[nlmixr]{dynmodelControl}} .
#' @param ... Other parameters (ignored)
#' @return A dynmodel fit object
#' @author Wenping Wang, Mason McComb and Matt Fidler
#' @examples
#'
#' \donttest{
#'
#' # dynmodel example --------------------------------------------------------
#' ode <- "
#' kel = CL/V;
#' d/dt(X) = -kel*X;
#' C=X/V;
#' PRED = C
#' "
#' ode_system <- RxODE(model = ode)
#' model_error_structure <- cp ~ C + add(0.01) + prop(0.01)
#' inits <- c(CL = 1, V = 10)
#' control <- dynmodelControl(method = "Nelder-Mead")
#' fit <-
#' try(dynmodel(
#' system = ode_system,
#' model = model_error_structure,
#' data = Bolus_1CPT,
#' inits = inits,
#' control = control
#' ))
#'
#' # nlmixr model example ----------------------------------------------------------
#' model_onecmt_bolus <- function() {
#' ini({
#' CL <- c(0, 5, 10) # Clearance (L/hr)
#' V <- c(0, 50, 100) # Volume of Distribution
#' prop.err <- c(0, 0.01, 1)
#' })
#' model({
#' kel <- CL / V
#' d / dt(X) <- -kel * X
#' cp <- X / V
#' cp ~ prop(prop.err)
#' })
#' }
#'
#' # note on some platforms this fit is not successful
#' fit <- try(nlmixr(object = model_onecmt_bolus, data = Bolus_1CPT, est = "dynmodel"))
#'
#' if (inherits(fit, "nlmixrDynmodel")) {
#' as.dynmodel(fit)
#' }
#'
#' # method = "focei" is slightly more flexible and well tested
#'
#' fit <- try(nlmixr(object = model_onecmt_bolus, data = Bolus_1CPT, est = "focei"))
#'
#' }
#' @export
dynmodel <- function(system, model, inits, data, fixPars = NULL, nlmixrObject = NULL, control = list(), ...) {
# Timing and environment --------------------------------------------------
.pt <- proc.time()
.time <- c()
.norm <- .dnorm <- .logn <- .dlnorm <- NULL
.dynmodel.env <- new.env(parent = emptyenv())
# dynmodelControl Handling ------------------------------------------------
if (!RxODE::rxIs(control, "dynmodelControl")) {
control <- do.call(dynmodelControl, control)
}
# reassign control names
for (i in 1:length(control)) {
assign(names(control[i]), control[[i]])
}
# Error model -------------------------------------------------------------
modelList <-
if (inherits(model, "formula")) {
list(model)
} else {
model
}
inits.err <- NULL
.env <- environment()
modelParsed <-
lapply(modelList, function(.model) {
.model <- unlist(lapply(attr(terms(.model), "variables"), as.list))
.model <- sapply(.model, deparse)
# assign error terms
.sigma.add <-
if ("add" %in% .model) {
as.numeric(.model[which(.model == "add") + 1])
} else {
NULL
}
.sigma.prop <-
if ("prop" %in% .model) {
as.numeric(.model[which(.model == "prop") + 1])
} else {
NULL
}
.sigma.pow <-
if ("pow" %in% .model) {
as.numeric(.model[which(.model == "pow") + 1])
} else {
NULL
}
.sigma.pow2 <-
if ("pow2" %in% .model) {
as.numeric(.model[which(.model == "pow2") + 1])
} else {
NULL
}
.sigma.yeoJohnson <-
if ("yeoJohnson" %in% .model) {
as.numeric(.model[which(.model == "yeoJohnson") + 1])
} else {
NULL
}
.sigma.boxCox <-
if ("boxCox" %in% .model) {
as.numeric(.model[which(.model == "boxCox") + 1])
} else {
NULL
}
.sigma.norm <-
if ("norm" %in% .model) {
assign(".norm", TRUE, .env)
as.numeric(.model[which(.model == "norm") + 1])
} else {
assign(".norm", NULL, .env)
NULL
}
.sigma.dnorm <-
if ("dnorm" %in% .model) {
assign(".dnorm", TRUE, .env)
as.numeric(.model[which(.model == "dnorm") + 1])
} else {
assign(".dnorm", NULL, .env)
NULL
}
.sigma.logn <-
if ("logn" %in% .model) {
assign(".logn", TRUE, .env)
as.numeric(.model[which(.model == "logn") + 1])
} else {
assign(".logn", NULL, .env)
NULL
}
.sigma.dlnorm <-
if ("dlnorm" %in% .model) {
assign(".dlnorm", TRUE, .env)
as.numeric(.model[which(.model == "dlnorm") + 1])
} else {
assign(".dlnorm", NULL, .env)
NULL
}
.sigma.tbs <-
if ("tbs" %in% .model) {
as.numeric(.model[which(.model == "tbs") + 1])
} else {
NULL
}
.sigma.tbsYj <-
if ("tbsYj" %in% .model) {
as.numeric(.model[which(.model == "tbsYj") + 1])
} else {
NULL
}
# keep error model terms
inits.err <-
c(
add = .sigma.add,
prop = .sigma.prop,
pow = .sigma.pow,
pow2 = .sigma.pow2,
yeoJohnson = .sigma.yeoJohnson,
boxCox = .sigma.boxCox,
norm = .sigma.norm,
dnorm = .sigma.dnorm,
tbs = .sigma.tbs,
tbsYj = .sigma.tbsYj
)
inits.err <- inits.err[which(names(inits.err) %in% intersect(names(inits.err), .model))]
assign("inits.err", inits.err, .env)
.model <- c("dv" = .model[2], "pred" = .model[3], inits.err)
})
inits <- c(inits, inits.err)
if ("pow2" %in% names(inits) & !("pow" %in% names(inits))) {
stop("Error Model: pow must be defined when using pow2")
}
# Check dynmodel() inputs, Define vars, modelVars, pars, ------------
# NOTES: Check to make sure all there is consistency between error model, data. inits, and ODE model
# data handling
## data <- RxODE::etTrans(data, system, addCmt = TRUE, dropUnits = TRUE, allTimeVar = TRUE)
.original.data <- data
# warn DV must be in data
if (!("DV" %in% names(data))) {
stop("data must contain column named DV")
}
# remove row that has time zero with zero observation, and no event
if (data$TIME[1] == 0 & data$EVID[1] == 0 & data$DV[1] == 0) {
rows <- -1
} else {
rows <- TRUE
}
# add model variable to data
.dv.name <- unlist(modelParsed)["dv"][[1]]
if (any(names(data) %in% .dv.name) == FALSE) {
data[[.dv.name]] <- data$DV
}
if (any(data$EVID %in% 2)) {
## warning("Removing EVID==2 rows from the data; they are not supported in dynmodel.")
data <- data[data$EVID != 2, ]
if (nrow(data) == 0) {
stop("Zero rows of data remain after removing EVID == 2.")
}
}
data0 <- data[data$EVID == 0, ]
nobst <- length(data0$DV)
# Error "model" contains "data" variables?
# check to see if there is a discrepency between error model names and data
nodef <- setdiff(sapply(modelParsed, function(x) x["dv"]), names(data))
# print error message
if (length(nodef) & is.null(nlmixrObject)) {
msg <- err.msg(nodef, pre = "var(s) not found in data: ")
stop(msg)
}
# "system" variables contain error "model" variables?
# obtain all variables from the system
modelVars <- system$cmpMgr$get.modelVars()
# reassign vars to combine state and lhs variables
vars <- c(modelVars$state, modelVars$lhs)
# Check to see if the prediction term is in the error model
nodef <- setdiff(sapply(modelParsed, function(x) x["pred"]), vars)
# print error message
if (length(nodef)) {
msg <- err.msg(nodef, pre = "modelVar(s) not found in model: ")
stop(msg)
}
# "system" variables contain estimated "init" variables and fixed "fixPars" variables?
# obtain fixed and estimated parameters
pars <-
if (is.null(nlmixrObject)) {
modelVars$params
} else {
names(
nlmixrDynmodelConvert(nlmixrObject)$inits
)
}