1
#' Fit one or more kinetic models with one or more state variables to one or
2
#' more datasets
3
#'
4
#' This function calls \code{\link{mkinfit}} on all combinations of models and
5
#' datasets specified in its first two arguments.
6
#'
7
#' @param models Either a character vector of shorthand names like
8
#'   \code{c("SFO", "FOMC", "DFOP", "HS", "SFORB")}, or an optionally named
9
#'   list of \code{\link{mkinmod}} objects.
10
#' @param datasets An optionally named list of datasets suitable as observed
11
#'   data for \code{\link{mkinfit}}.
12
#' @param cores The number of cores to be used for multicore processing. This
13
#'   is only used when the \code{cluster} argument is \code{NULL}. On Windows
14
#'   machines, cores > 1 is not supported, you need to use the \code{cluster}
15
#'   argument to use multiple logical processors. Per default, all cores
16
#'   detected by [parallel::detectCores()] are used.
17
#' @param cluster A cluster as returned by \code{\link{makeCluster}} to be used
18
#'   for parallel execution.
19
#' @param \dots Further arguments that will be passed to \code{\link{mkinfit}}.
20
#' @importFrom parallel mclapply parLapply detectCores
21
#' @return A two-dimensional \code{\link{array}} of \code{\link{mkinfit}}
22
#'   objects and/or try-errors that can be indexed using the model names for the
23
#'   first index (row index) and the dataset names for the second index (column
24
#'   index).
25
#' @author Johannes Ranke
26
#' @seealso \code{\link{[.mmkin}} for subsetting, \code{\link{plot.mmkin}} for
27
#'   plotting.
28
#' @keywords optimize
29
#' @examples
30
#'
31
#' \dontrun{
32
#' m_synth_SFO_lin <- mkinmod(parent = mkinsub("SFO", "M1"),
33
#'                            M1 = mkinsub("SFO", "M2"),
34
#'                            M2 = mkinsub("SFO"), use_of_ff = "max")
35
#'
36
#' m_synth_FOMC_lin <- mkinmod(parent = mkinsub("FOMC", "M1"),
37
#'                             M1 = mkinsub("SFO", "M2"),
38
#'                             M2 = mkinsub("SFO"), use_of_ff = "max")
39
#'
40
#' models <- list(SFO_lin = m_synth_SFO_lin, FOMC_lin = m_synth_FOMC_lin)
41
#' datasets <- lapply(synthetic_data_for_UBA_2014[1:3], function(x) x$data)
42
#' names(datasets) <- paste("Dataset", 1:3)
43
#'
44
#' time_default <- system.time(fits.0 <- mmkin(models, datasets, quiet = TRUE))
45
#' time_1 <- system.time(fits.4 <- mmkin(models, datasets, cores = 1, quiet = TRUE))
46
#'
47
#' time_default
48
#' time_1
49
#'
50
#' endpoints(fits.0[["SFO_lin", 2]])
51
#'
52
#' # plot.mkinfit handles rows or columns of mmkin result objects
53
#' plot(fits.0[1, ])
54
#' plot(fits.0[1, ], obs_var = c("M1", "M2"))
55
#' plot(fits.0[, 1])
56
#' # Use double brackets to extract a single mkinfit object, which will be plotted
57
#' # by plot.mkinfit and can be plotted using plot_sep
58
#' plot(fits.0[[1, 1]], sep_obs = TRUE, show_residuals = TRUE, show_errmin = TRUE)
59
#' plot_sep(fits.0[[1, 1]])
60
#' # Plotting with mmkin (single brackets, extracting an mmkin object) does not
61
#' # allow to plot the observed variables separately
62
#' plot(fits.0[1, 1])
63
#'
64
#' # On Windows, we can use multiple cores by making a cluster using the parallel
65
#' # package, which gets loaded with mkin, and passing it to mmkin, e.g.
66
#' cl <- makePSOCKcluster(12)
67
#' f <- mmkin(c("SFO", "FOMC", "DFOP"),
68
#'   list(A = FOCUS_2006_A, B = FOCUS_2006_B, C = FOCUS_2006_C, D = FOCUS_2006_D),
69
#'   cluster = cl, quiet = TRUE)
70
#' print(f)
71
#' # We get false convergence for the FOMC fit to FOCUS_2006_A because this
72
#' # dataset is really SFO, and the FOMC fit is overparameterised
73
#' stopCluster(cl)
74
#' }
75
#'
76
#' @export mmkin
77
mmkin <- function(models = c("SFO", "FOMC", "DFOP"), datasets,
78
  cores = parallel::detectCores(), cluster = NULL, ...)
79
{
80 2
  call <- match.call()
81 2
  parent_models_available = c("SFO", "FOMC", "DFOP", "HS", "SFORB", "IORE", "logistic")
82 2
  n.m <- length(models)
83 2
  n.d <- length(datasets)
84 2
  n.fits <- n.m * n.d
85 2
  fit_indices <- matrix(1:n.fits, ncol = n.d)
86

87
  # Check models and define their names
88 2
  if (!all(sapply(models, function(x) inherits(x, "mkinmod")))) {
89 2
    if (!all(models %in% parent_models_available)) {
90 0
      stop("Please supply models as a list of mkinmod objects or a vector combined of\n  ",
91 0
           paste(parent_models_available, collapse = ", "))
92
    } else {
93 2
      names(models) <- models
94
    }
95
  } else {
96 0
    if (is.null(names(models))) names(models) <- as.character(1:n.m)
97
  }
98

99
  # Check datasets and define their names
100 2
  if (is.null(names(datasets))) names(datasets) <- as.character(1:n.d)
101

102
  # Define names for fit index
103 2
  dimnames(fit_indices) <- list(model = names(models),
104 2
                                dataset = names(datasets))
105

106

107 2
  fit_function <- function(fit_index) {
108 2
    w <- which(fit_indices == fit_index, arr.ind = TRUE)
109 2
    model_index <- w[1]
110 2
    dataset_index <- w[2]
111 2
    res <- try(mkinfit(models[[model_index]], datasets[[dataset_index]], ...))
112 2
    if (!inherits(res, "try-error")) res$mkinmod$name <- names(models)[model_index]
113 2
    return(res)
114
  }
115

116 2
  if (is.null(cluster)) {
117 2
    results <- parallel::mclapply(as.list(1:n.fits), fit_function,
118 2
      mc.cores = cores, mc.preschedule = FALSE)
119
  } else {
120 0
    results <- parallel::parLapply(cluster, as.list(1:n.fits), fit_function)
121
  }
122

123 2
  attributes(results) <- attributes(fit_indices)
124 2
  attr(results, "call") <- call
125 2
  class(results) <- "mmkin"
126 2
  return(results)
127
}
128

129
#' Subsetting method for mmkin objects
130
#'
131
#' @param x An \code{\link{mmkin} object}
132
#' @param i Row index selecting the fits for specific models
133
#' @param j Column index selecting the fits to specific datasets
134
#' @param ... Not used, only there to satisfy the generic method definition
135
#' @param drop If FALSE, the method always returns an mmkin object, otherwise
136
#'   either a list of mkinfit objects or a single mkinfit object.
137
#' @return An object of class \code{\link{mmkin}}.
138
#' @author Johannes Ranke
139
#' @rdname Extract.mmkin
140
#' @examples
141
#'
142
#'   # Only use one core, to pass R CMD check --as-cran
143
#'   fits <- mmkin(c("SFO", "FOMC"), list(B = FOCUS_2006_B, C = FOCUS_2006_C),
144
#'                 cores = 1, quiet = TRUE)
145
#'   fits["FOMC", ]
146
#'   fits[, "B"]
147
#'   fits["SFO", "B"]
148
#'
149
#'   head(
150
#'     # This extracts an mkinfit object with lots of components
151
#'     fits[["FOMC", "B"]]
152
#'   )
153
#' @export
154
`[.mmkin` <- function(x, i, j, ..., drop = FALSE) {
155 2
  class(x) <- NULL
156 2
  x_sub <- x[i, j, drop = drop]
157 2
  if (!drop) class(x_sub) <- "mmkin"
158 2
  return(x_sub)
159
}
160

161
#' Print method for mmkin objects
162
#'
163
#' @param x An [mmkin] object.
164
#' @param \dots Not used.
165
#' @export
166
print.mmkin <- function(x, ...) {
167 0
  cat("<mmkin> object\n")
168 0
  cat("Status of individual fits:\n\n")
169 0
  all_summary_warnings <- character()
170 0
  sww <- 0 # Counter for Shapiro-Wilks warnings
171

172 0
  display <- lapply(x,
173 0
    function(fit) {
174 0
      if (inherits(fit, "try-error")) return("E")
175 0
      sw <- fit$summary_warnings
176 0
      swn <- names(sw)
177 0
      if (length(sw) > 0) {
178 0
        if (any(grepl("S", swn))) {
179 0
          sww <<- sww + 1
180 0
          swn <- gsub("S", paste0("S", sww), swn)
181
        }
182 0
        warnstring <- paste(swn, collapse = ", ")
183 0
        names(sw) <- swn
184 0
        all_summary_warnings <<- c(all_summary_warnings, sw)
185 0
        return(warnstring)
186
      } else {
187 0
        return("OK")
188
      }
189
    })
190 0
  display <- unlist(display)
191 0
  dim(display) <- dim(x)
192 0
  dimnames(display) <- dimnames(x)
193 0
  print(display, quote = FALSE)
194

195 0
  cat("\n")
196 0
  if (any(display == "OK")) cat("OK: No warnings\n")
197 0
  if (any(display == "E")) cat("E: Error\n")
198 0
  u_swn <- unique(names(all_summary_warnings))
199 0
  u_w <- all_summary_warnings[u_swn]
200 0
  for (i in seq_along(u_w)) {
201 0
    cat(names(u_w)[i], ": ", u_w[i], "\n", sep = "")
202
  }
203

204
}
205

206
#' @export
207
update.mmkin <- function(object, ..., evaluate = TRUE)
208
{
209 0
  call <- attr(object, "call")
210

211 0
  update_arguments <- match.call(expand.dots = FALSE)$...
212

213 0
  if (length(update_arguments) > 0) {
214 0
    update_arguments_in_call <- !is.na(match(names(update_arguments), names(call)))
215
  }
216

217 0
  for (a in names(update_arguments)[update_arguments_in_call]) {
218 0
    call[[a]] <- update_arguments[[a]]
219
  }
220

221 0
  update_arguments_not_in_call <- !update_arguments_in_call
222 0
  if(any(update_arguments_not_in_call)) {
223 0
    call <- c(as.list(call), update_arguments[update_arguments_not_in_call])
224 0
    call <- as.call(call)
225
  }
226

227 0
  if(evaluate) eval(call, parent.frame())
228 0
  else call
229
}

Read our documentation on viewing source code .

Loading