-
Notifications
You must be signed in to change notification settings - Fork 89
/
misc.R
542 lines (467 loc) · 15.5 KB
/
misc.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
#' Prepend a new class
#'
#' This adds an extra class to a base class of "model_spec".
#'
#' @param prefix A character string for a class.
#' @return A character vector.
#' @keywords internal
#' @export
make_classes <- function(prefix) {
c(prefix, "model_spec")
}
#' Check to ensure that ellipses are empty
#' @param ... Extra arguments.
#' @return If an error is not thrown (from non-empty ellipses), a NULL list.
#' @keywords internal
#' @export
check_empty_ellipse <- function(...) {
terms <- quos(...)
if (!is_empty(terms)) {
rlang::abort("Please pass other arguments to the model function via `set_engine()`.")
}
terms
}
is_missing_arg <- function(x) {
identical(x, quote(missing_arg()))
}
# return a condition for use in `dplyr::filter()` on model info.
# if the user specified an engine and the model object reflects that in
# the `user_specified_engine` slot, filter the model info down to
# those that the user specified. if not, don't filter the model info at all.
#
# note that, model objects generated pre parsnip 1.0.2, or from extensions
# that don't implement the `user_specified_engine` slot, will not trigger
# these checks.
engine_filter_condition <- function(engine, user_specified_engine) {
# use !isTRUE so that result is TRUE if is.null(user_specified_engine)
if (!isTRUE(user_specified_engine) || is.null(engine)) {
return(TRUE)
}
rlang::quo(engine == !!engine)
}
# analogous helper for modes to `engine_filter_condition()`
mode_filter_condition <- function(mode, user_specified_mode) {
# use !isTRUE so that result is TRUE if is.null(user_specified_mode)
if (!isTRUE(user_specified_mode) || is.null(mode)) {
return(TRUE)
}
rlang::quo(mode == !!mode)
}
#' Model Specification Checking:
#'
#' The helpers `spec_is_possible()`, `spec_is_loaded()`, and
#' `prompt_missing_implementation()` provide tooling for checking
#' model specifications. In addition to the `spec`, `engine`, and `mode`
#' arguments, the functions take arguments `user_specified_engine` and
#' `user_specified_mode`, denoting whether the user themselves has
#' specified the engine or mode, respectively.
#'
#' `spec_is_possible()` checks against the union of
#'
#' * the current parsnip model environment and
#' * the `model_info_table` of "pre-registered" model specifications
#'
#' to determine whether a model is well-specified. See
#' `parsnip:::read_model_info_table()` for this table.
#'
#' `spec_is_loaded()` checks only against the current parsnip model environment.
#'
#' `spec_is_possible()` is executed automatically on `new_model_spec()`,
#' `set_mode()`, and `set_engine()`, and `spec_is_loaded()` is executed
#' automatically in `print.model_spec()`, among other places. `spec_is_possible()`
#' should be used when a model specification is still "in progress" of being
#' specified, while `spec_is_loaded` should only be called when parsnip or an
#' extension receives some indication that the user is "done" specifying a model
#' specification: at print, fit, addition to a workflow, or `extract_*()`, for
#' example.
#'
#' When `spec_is_loaded()` is `FALSE`, the `prompt_missing_implementation()`
#' helper will construct an informative message to prompt users to load or
#' install needed packages. It's `prompt` argument refers to the prompting
#' function to use, usually [cli::cli_inform] or [cli::cli_abort], and the
#' ellipses are passed to that function.
#' @export
#' @keywords internal
#' @rdname extension-check-helpers
spec_is_possible <- function(spec,
engine = spec$engine,
user_specified_engine = spec$user_specified_engine,
mode = spec$mode,
user_specified_mode = spec$user_specified_mode) {
cls <- class(spec)[[1]]
all_model_info <-
dplyr::full_join(
read_model_info_table(),
rlang::env_get(get_model_env(), cls) %>% dplyr::mutate(model = cls),
by = c("model", "engine", "mode")
)
engine_condition <- engine_filter_condition(engine, user_specified_engine)
mode_condition <- mode_filter_condition(mode, user_specified_mode)
possibilities <-
all_model_info %>%
dplyr::filter(
model == cls,
!!engine_condition,
!!mode_condition
)
return(nrow(possibilities) > 0)
}
# see ?add_on_exports for more information on usage
#' @export
#' @keywords internal
#' @rdname extension-check-helpers
spec_is_loaded <- function(spec,
engine = spec$engine,
user_specified_engine = spec$user_specified_engine,
mode = spec$mode,
user_specified_mode = spec$user_specified_mode) {
cls <- class(spec)[[1]]
engine_condition <- engine_filter_condition(engine, user_specified_engine)
mode_condition <- mode_filter_condition(mode, user_specified_mode)
avail <- get_from_env(cls)
if (is.null(avail)) {
return(FALSE)
}
avail <- avail %>%
dplyr::filter(!!mode_condition, !!engine_condition)
if (nrow(avail) > 0) {
return(TRUE)
}
FALSE
}
is_printable_spec <- function(x) {
!is.null(x$method$fit$args) &&
spec_is_loaded(x)
}
# construct a message informing the user that there are no
# implementations for the current model spec / mode / engine.
#
# if there's a "pre-registered" extension supporting that setup,
# nudge the user to install/load it.
#
# see ?add_on_exports for more information on usage
#' @export
#' @keywords internal
#' @rdname extension-check-helpers
prompt_missing_implementation <- function(spec,
engine = spec$engine,
user_specified_engine = spec$user_specified_engine,
mode = spec$mode,
user_specified_mode = spec$user_specified_mode,
prompt, ...) {
cls <- class(spec)[[1]]
engine_condition <- engine_filter_condition(engine, user_specified_engine)
mode_condition <- mode_filter_condition(mode, user_specified_mode)
avail <- get_from_env(cls)
if (!is.null(avail)) {
avail <-
avail %>%
dplyr::filter(!!mode_condition, !!engine_condition)
}
all <-
read_model_info_table() %>%
dplyr::filter(model == cls, !!mode_condition, !!engine_condition, !is.na(pkg)) %>%
dplyr::select(-model)
if (!isTRUE(user_specified_mode)) {mode <- ""}
msg <- c(
"!" = "{.pkg parsnip} could not locate an implementation for `{cls}` {mode} \\
model specifications{if (isTRUE(user_specified_engine)) {
paste0(' using the `', engine, '` engine')} else {''}}."
)
if (nrow(avail) == 0 && nrow(all) > 0) {
pkgs <- unique(all$pkg)
msg <-
c(
msg,
"i" = paste0("{cli::qty(pkgs)}The parsnip extension package{?s} {.pkg {pkgs}}",
" implemen{?ts/t} support for this specification."),
"i" = "Please install (if needed) and load to continue."
)
}
prompt(c(msg, ""), ...)
}
#' Print the model call
#'
#' @param x A "model_spec" object.
#' @return A character string.
#' @keywords internal
#' @export
show_call <- function(object) {
object$method$fit$args <-
map(object$method$fit$args, convert_arg)
call2(object$method$fit$func["fun"],
!!!object$method$fit$args,
.ns = object$method$fit$func["pkg"]
)
}
convert_arg <- function(x) {
if (is_quosure(x)) {
quo_get_expr(x)
} else {
x
}
}
levels_from_formula <- function(f, dat) {
if (inherits(dat, "tbl_spark")) {
res <- NULL
} else {
res <- levels(eval_tidy(f[[2]], dat))
}
res
}
#' @export
#' @keywords internal
#' @rdname add_on_exports
show_fit <- function(model, eng) {
mod <- translate(x = model, engine = eng)
fit_call <- show_call(mod)
call_text <- deparse(fit_call)
call_text <- paste0(call_text, collapse = "\n")
paste0(
"\\preformatted{\n",
call_text,
"\n}\n\n"
)
}
# Check non-translated core arguments
# Each model has its own definition of this
check_args <- function(object) {
UseMethod("check_args")
}
check_args.default <- function(object) {
invisible(object)
}
# ------------------------------------------------------------------------------
# copied form recipes
names0 <- function(num, prefix = "x") {
if (num < 1) {
rlang::abort("`num` should be > 0.")
}
ind <- format(1:num)
ind <- gsub(" ", "0", ind)
paste0(prefix, ind)
}
# ------------------------------------------------------------------------------
#' @export
#' @keywords internal
#' @rdname add_on_exports
update_dot_check <- function(...) {
dots <- enquos(...)
if (length(dots) > 0) {
rlang::abort(
glue::glue(
"Extra arguments will be ignored: ",
glue::glue_collapse(glue::glue("`{names(dots)}`"), sep = ", ")
)
)
}
invisible(NULL)
}
# ------------------------------------------------------------------------------
#' @export
#' @keywords internal
#' @rdname add_on_exports
new_model_spec <- function(cls, args, eng_args, mode, user_specified_mode = TRUE,
method, engine, user_specified_engine = TRUE) {
# determine if the model specification could feasibly match any entry
# in the union of the parsnip model environment and model_info_table.
# if not, trigger an error based on the (possibly inferred) model spec slots.
out <- list(
args = args, eng_args = eng_args,
mode = mode, user_specified_mode = user_specified_mode, method = method,
engine = engine, user_specified_engine = user_specified_engine
)
class(out) <- make_classes(cls)
if (!spec_is_possible(spec = out)) {
check_spec_mode_engine_val(cls, engine, mode, call = caller_env())
}
out
}
# ------------------------------------------------------------------------------
check_outcome <- function(y, spec) {
if (spec$mode == "unknown") {
return(invisible(NULL))
}
if (spec$mode == "regression") {
outcome_is_numeric <- if (is.atomic(y)) {is.numeric(y)} else {all(map_lgl(y, is.numeric))}
if (!outcome_is_numeric) {
rlang::abort("For a regression model, the outcome should be numeric.")
}
}
if (spec$mode == "classification") {
outcome_is_factor <- if (is.atomic(y)) {is.factor(y)} else {all(map_lgl(y, is.factor))}
if (!outcome_is_factor) {
rlang::abort("For a classification model, the outcome should be a factor.")
}
}
if (spec$mode == "censored regression") {
outcome_is_surv <- inherits(y, "Surv")
if (!outcome_is_surv) {
rlang::abort("For a censored regression model, the outcome should be a `Surv` object.")
}
}
invisible(NULL)
}
# ------------------------------------------------------------------------------
#' @export
#' @keywords internal
#' @rdname add_on_exports
check_final_param <- function(x) {
if (is.null(x)) {
return(invisible(x))
}
if (!is.list(x) & !tibble::is_tibble(x)) {
rlang::abort("The parameter object should be a list or tibble")
}
if (tibble::is_tibble(x) && nrow(x) > 1) {
rlang::abort("The parameter tibble should have a single row.")
}
if (tibble::is_tibble(x)) {
x <- as.list(x)
}
if (length(names) == 0 || any(names(x) == "")) {
rlang::abort("All values in `parameters` should have a name.")
}
invisible(x)
}
#' @export
#' @keywords internal
#' @rdname add_on_exports
update_main_parameters <- function(args, param) {
if (length(param) == 0) {
return(args)
}
if (length(args) == 0) {
return(param)
}
# In case an engine argument is included:
has_extra_args <- !(names(param) %in% names(args))
extra_args <- names(param)[has_extra_args]
if (any(has_extra_args)) {
rlang::abort(
paste(
"At least one argument is not a main argument:",
paste0("`", extra_args, "`", collapse = ", ")
)
)
}
param <- param[!has_extra_args]
args <- utils::modifyList(args, param)
}
#' @export
#' @keywords internal
#' @rdname add_on_exports
update_engine_parameters <- function(eng_args, fresh, ...) {
dots <- enquos(...)
## only update from dots when there are eng args in original model spec
if (is_null(eng_args) || (fresh && length(dots) == 0)) {
ret <- NULL
} else {
ret <- utils::modifyList(eng_args, dots)
}
has_extra_dots <- !(names(dots) %in% names(eng_args))
dots <- dots[has_extra_dots]
update_dot_check(!!!dots)
ret
}
# ------------------------------------------------------------------------------
# Since stan changed the function interface
#' Wrapper for stan confidence intervals
#' @param object A stan model fit
#' @param newdata A data set.
#' @export
#' @keywords internal
stan_conf_int <- function(object, newdata) {
check_installs(list(method = list(libs = "rstanarm")))
if (utils::packageVersion("rstanarm") >= "2.21.1") {
fn <- rlang::call2("posterior_epred",
.ns = "rstanarm",
object = expr(object),
newdata = expr(newdata),
seed = expr(sample.int(10^5, 1))
)
} else {
fn <- rlang::call2("posterior_linpred",
.ns = "rstanarm",
object = expr(object),
newdata = expr(newdata),
transform = TRUE,
seed = expr(sample.int(10^5, 1))
)
}
rlang::eval_tidy(fn)
}
# ------------------------------------------------------------------------------
#' Helper functions for checking the penalty of glmnet models
#'
#' @description
#' These functions are for developer use.
#'
#' `.check_glmnet_penalty_fit()` checks that the model specification for fitting a
#' glmnet model contains a single value.
#'
#' `.check_glmnet_penalty_predict()` checks that the penalty value used for prediction is valid.
#' If called by `predict()`, it needs to be a single value. Multiple values are
#' allowed for `multi_predict()`.
#'
#' @param x An object of class `model_spec`.
#' @rdname glmnet_helpers
#' @keywords internal
#' @export
.check_glmnet_penalty_fit <- function(x) {
pen <- rlang::eval_tidy(x$args$penalty)
if (length(pen) != 1) {
rlang::abort(c(
"For the glmnet engine, `penalty` must be a single number (or a value of `tune()`).",
glue::glue("There are {length(pen)} values for `penalty`."),
"To try multiple values for total regularization, use the tune package.",
"To predict multiple penalties, use `multi_predict()`"
))
}
}
#' @param penalty A penalty value to check.
#' @param object An object of class `model_fit`.
#' @param multi A logical indicating if multiple values are allowed.
#'
#' @rdname glmnet_helpers
#' @keywords internal
#' @export
.check_glmnet_penalty_predict <- function(penalty = NULL, object, multi = FALSE) {
if (is.null(penalty)) {
penalty <- object$fit$lambda
}
# when using `predict()`, allow for a single lambda
if (!multi) {
if (length(penalty) != 1) {
rlang::abort(
glue::glue(
"`penalty` should be a single numeric value. `multi_predict()` ",
"can be used to get multiple predictions per row of data.",
)
)
}
}
if (length(object$fit$lambda) == 1 && penalty != object$fit$lambda) {
rlang::abort(
glue::glue(
"The glmnet model was fit with a single penalty value of ",
"{object$fit$lambda}. Predicting with a value of {penalty} ",
"will give incorrect results from `glmnet()`."
)
)
}
penalty
}
check_case_weights <- function(x, spec) {
if (is.null(x) | spec$engine == "spark") {
return(invisible(NULL))
}
if (!hardhat::is_case_weights(x)) {
rlang::abort("'case_weights' should be a single numeric vector of class 'hardhat_case_weights'.")
}
allowed <- case_weights_allowed(spec)
if (!allowed) {
rlang::abort("Case weights are not enabled by the underlying model implementation.")
}
invisible(NULL)
}