## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")

## ----eval=requireNamespace("rpart", quietly=TRUE)-----------------------------
library(SynthesizerPlus)
set.seed(31)
x <- runif(500, -2, 2)
d <- data.frame(x = x, y = sin(3 * x) + 0.3 * rnorm(500))

base <- fit_synthesizer(d, seed = 1)
hybrid <- fit_synthesizer(d, nonlinear_target = "y",
                          nonlinear_minbucket = 15, seed = 1)
original_draw <- generate(base, n = 500, seed = 2)
hybrid_draw <- generate(hybrid, n = 500, seed = 2)

# Compare nonlinear curves and marginal error without treating a plot as
# proof of general superiority.
plot(d$x, d$y, col = grDevices::adjustcolor("black", 0.25),
     xlab = "x", ylab = "y", main = "Nonlinear response")
points(original_draw$x, original_draw$y, col = "red", pch = 3)
points(hybrid_draw$x, hybrid_draw$y, col = "blue", pch = 1)
legend("topleft", c("original", "copula", "hybrid"),
       col = c("black", "red", "blue"), pch = c(1, 3, 1), bty = "n")

## ----hybrid-ablation-demo, eval=FALSE-----------------------------------------
# fit <- fit_synthesizer(d, nonlinear_target = "y", seed = 101,
#                        nonlinear_residual = "global",
#                        nonlinear_calibration = "none")
# synthetic <- generate(fit, n = nrow(d), seed = 202)

## ----gam-hybrid, eval=requireNamespace("mgcv", quietly=TRUE)------------------
fit_gam <- fit_synthesizer(d, nonlinear_target = "y",
                           nonlinear_engine = "gam",
                           nonlinear_gam_k = 10,
                           nonlinear_residual = "leaf",
                           nonlinear_calibration = "quantile", seed = 1)
syn_gam <- generate(fit_gam, n = 500, seed = 2)
stopifnot(nrow(syn_gam) == 500)

## ----auto-engine-example, eval=FALSE------------------------------------------
# fit_auto <- fit_synthesizer(
#   d, nonlinear_target = "y", nonlinear_engine = "auto",
#   nonlinear_cv_folds = 5L, nonlinear_cv_rule = "one_se",
#   seed = 101
# )
# fit_auto$pooled$nonlinear$selection$scores
# fit_auto$pooled$nonlinear$selection$selected
# syn_auto <- generate(fit_auto, n = nrow(d), seed = 102)

