jranke / mkin
1
#' Helper functions to create nlme models from mmkin row objects
2
#'
3
#' These functions facilitate setting up a nonlinear mixed effects model for
4
#' an mmkin row object. An mmkin row object is essentially a list of mkinfit
5
#' objects that have been obtained by fitting the same model to a list of
6
#' datasets. They are used internally by the [nlme.mmkin()] method.
7
#'
8
#' @param object An mmkin row object containing several fits of the same model to different datasets
9
#' @import nlme
10
#' @rdname nlme
11
#' @seealso \code{\link{nlme.mmkin}}
12
#' @examples
13
#' sampling_times = c(0, 1, 3, 7, 14, 28, 60, 90, 120)
14
#' m_SFO <- mkinmod(parent = mkinsub("SFO"))
15
#' d_SFO_1 <- mkinpredict(m_SFO,
16
#'   c(k_parent = 0.1),
17
#'   c(parent = 98), sampling_times)
18
#' d_SFO_1_long <- mkin_wide_to_long(d_SFO_1, time = "time")
19
#' d_SFO_2 <- mkinpredict(m_SFO,
20
#'   c(k_parent = 0.05),
21
#'   c(parent = 102), sampling_times)
22
#' d_SFO_2_long <- mkin_wide_to_long(d_SFO_2, time = "time")
23
#' d_SFO_3 <- mkinpredict(m_SFO,
24
#'   c(k_parent = 0.02),
25
#'   c(parent = 103), sampling_times)
26
#' d_SFO_3_long <- mkin_wide_to_long(d_SFO_3, time = "time")
27
#'
28
#' d1 <- add_err(d_SFO_1, function(value) 3, n = 1)
29
#' d2 <- add_err(d_SFO_2, function(value) 2, n = 1)
30
#' d3 <- add_err(d_SFO_3, function(value) 4, n = 1)
31
#' ds <- c(d1 = d1, d2 = d2, d3 = d3)
32
#'
33
#' f <- mmkin("SFO", ds, cores = 1, quiet = TRUE)
34
#' mean_dp <- mean_degparms(f)
35
#' grouped_data <- nlme_data(f)
36
#' nlme_f <- nlme_function(f)
37
#' # These assignments are necessary for these objects to be
38
#' # visible to nlme and augPred when evaluation is done by
39
#' # pkgdown to generated the html docs.
40
#' assign("nlme_f", nlme_f, globalenv())
41
#' assign("grouped_data", grouped_data, globalenv())
42
#'
43
#' library(nlme)
44
#' m_nlme <- nlme(value ~ nlme_f(name, time, parent_0, log_k_parent_sink),
45
#'   data = grouped_data,
46
#'   fixed = parent_0 + log_k_parent_sink ~ 1,
47
#'   random = pdDiag(parent_0 + log_k_parent_sink ~ 1),
48
#'   start = mean_dp)
49
#' summary(m_nlme)
50
#' plot(augPred(m_nlme, level = 0:1), layout = c(3, 1))
51
#' # augPred does not work on fits with more than one state
52
#' # variable
53
#' #
54
#' # The procedure is greatly simplified by the nlme.mmkin function
55
#' f_nlme <- nlme(f)
56
#' plot(f_nlme)
57
#' @return A function that can be used with nlme
58
#' @export
59
nlme_function <- function(object) {
60 0
  if (nrow(object) > 1) stop("Only row objects allowed")
61

62 1
  mkin_model <- object[[1]]$mkinmod
63

64 1
  degparm_names <- names(mean_degparms(object))
65

66
  # Inspired by https://stackoverflow.com/a/12983961/3805440
67
  # and https://stackoverflow.com/a/26280789/3805440
68 1
  model_function_alist <- replicate(length(degparm_names) + 2, substitute())
69 1
  names(model_function_alist) <- c("name", "time", degparm_names)
70

71 1
  model_function_body <- quote({
72 1
    arg_frame <- as.data.frame(as.list((environment())), stringsAsFactors = FALSE)
73 1
    res_frame <- arg_frame[1:2]
74 1
    parm_frame <- arg_frame[-(1:2)]
75 1
    parms_unique <- unique(parm_frame)
76

77 1
    n_unique <- nrow(parms_unique)
78

79 1
    times_ds <- list()
80 1
    names_ds <- list()
81 1
    for (i in 1:n_unique) {
82 1
      times_ds[[i]] <-
83 1
        arg_frame[which(arg_frame[[3]] == parms_unique[i, 1]), "time"]
84 1
      names_ds[[i]] <-
85 1
        arg_frame[which(arg_frame[[3]] == parms_unique[i, 1]), "name"]
86
    }
87

88 1
    res_list <- lapply(1:n_unique, function(x) {
89 1
      transparms_optim <- unlist(parms_unique[x, , drop = TRUE])
90 1
      parms_fixed <- object[[1]]$bparms.fixed
91

92 1
      odeini_optim_parm_names <- grep('_0$', names(transparms_optim), value = TRUE)
93 1
      odeini_optim <- transparms_optim[odeini_optim_parm_names]
94 1
      names(odeini_optim) <- gsub('_0$', '', odeini_optim_parm_names)
95 1
      odeini_fixed_parm_names <- grep('_0$', names(parms_fixed), value = TRUE)
96 1
      odeini_fixed <- parms_fixed[odeini_fixed_parm_names]
97 1
      names(odeini_fixed) <- gsub('_0$', '', odeini_fixed_parm_names)
98 1
      odeini <- c(odeini_optim, odeini_fixed)[names(mkin_model$diffs)]
99

100 1
      ode_transparms_optim_names <- setdiff(names(transparms_optim), odeini_optim_parm_names)
101 1
      odeparms_optim <- backtransform_odeparms(transparms_optim[ode_transparms_optim_names], mkin_model,
102 1
        transform_rates = object[[1]]$transform_rates,
103 1
        transform_fractions = object[[1]]$transform_fractions)
104 1
      odeparms_fixed_names <- setdiff(names(parms_fixed), odeini_fixed_parm_names)
105 1
      odeparms_fixed <- parms_fixed[odeparms_fixed_names]
106 1
      odeparms <- c(odeparms_optim, odeparms_fixed)
107

108 1
      out_wide <- mkinpredict(mkin_model,
109 1
        odeparms = odeparms, odeini = odeini,
110 1
        solution_type = object[[1]]$solution_type,
111 1
        outtimes = sort(unique(times_ds[[x]])))
112 1
      out_array <- out_wide[, -1, drop = FALSE]
113 1
      rownames(out_array) <- as.character(unique(times_ds[[x]]))
114 1
      out_times <- as.character(times_ds[[x]])
115 1
      out_names <- as.character(names_ds[[x]])
116 1
      out_values <- mapply(function(times, names) out_array[times, names],
117 1
        out_times, out_names)
118 1
      return(as.numeric(out_values))
119
    })
120 1
    res <- unlist(res_list)
121 1
    return(res)
122
  })
123 1
  model_function <- as.function(c(model_function_alist, model_function_body))
124 1
  return(model_function)
125
}
126

127
#' @rdname nlme
128
#' @return If random is FALSE (default), a named vector containing mean values
129
#'   of the fitted degradation model parameters. If random is TRUE, a list with
130
#'   fixed and random effects, in the format required by the start argument of
131
#'   nlme for the case of a single grouping variable ds.
132
#' @param random Should a list with fixed and random effects be returned?
133
#' @export
134
mean_degparms <- function(object, random = FALSE) {
135 0
  if (nrow(object) > 1) stop("Only row objects allowed")
136 1
  parm_mat_trans <- sapply(object, parms, transformed = TRUE)
137 1
  mean_degparm_names <- setdiff(rownames(parm_mat_trans), names(object[[1]]$errparms))
138 1
  degparm_mat_trans <- parm_mat_trans[mean_degparm_names, , drop = FALSE]
139 1
  fixed <- apply(degparm_mat_trans, 1, mean)
140 1
  if (random) {
141 1
    random <- t(apply(degparm_mat_trans[mean_degparm_names, , drop = FALSE], 2, function(column) column - fixed))
142
    # If we only have one parameter, apply returns a vector so we get a single row
143 0
    if (nrow(degparm_mat_trans) == 1) random <- t(random)
144 1
    rownames(random) <- levels(nlme_data(object)$ds)
145 1
    return(list(fixed = fixed, random = list(ds = random)))
146
  } else {
147 1
    return(fixed)
148
  }
149
}
150

151
#' @rdname nlme
152
#' @importFrom purrr map_dfr
153
#' @return A \code{\link{groupedData}} object
154
#' @export
155
nlme_data <- function(object) {
156 0
  if (nrow(object) > 1) stop("Only row objects allowed")
157 1
  ds_names <- colnames(object)
158

159 1
  ds_list <- lapply(object, function(x) x$data[c("time", "variable", "observed")])
160 1
  names(ds_list) <- ds_names
161 1
  ds_nlme <- purrr::map_dfr(ds_list, function(x) x, .id = "ds")
162 1
  ds_nlme$variable <- as.character(ds_nlme$variable)
163 1
  ds_nlme$ds <- ordered(ds_nlme$ds, levels = unique(ds_nlme$ds))
164 1
  ds_nlme_renamed <- data.frame(ds = ds_nlme$ds, name = ds_nlme$variable,
165 1
    time = ds_nlme$time, value = ds_nlme$observed,
166 1
    stringsAsFactors = FALSE)
167 1
  ds_nlme_grouped <- groupedData(value ~ time | ds, ds_nlme_renamed, order.groups = FALSE)
168 1
  return(ds_nlme_grouped)
169
}

Read our documentation on viewing source code .

Loading