# check_installation.R: installs the packages needed in the lab and runs a short test.
# Run it before the lab: Rscript check_installation.R

options(repos = c(CRAN = "https://cloud.r-project.org"),
        timeout = 900)  # large packages need more than the default 60 s to download

if (getRversion() < "4.6.1") stop("Please install R 4.6.1 or newer.")

# On a shared computer (e.g. in the lab) the system library is read-only:
# install into the personal library instead, without asking.
probe <- file.path(.libPaths()[1], paste0("_test_", Sys.getpid()))
if (suppressWarnings(dir.create(probe))) {
  unlink(probe, recursive = TRUE)
} else {
  user_lib <- strsplit(Sys.getenv("R_LIBS_USER"), .Platform$path.sep)[[1]][1]
  dir.create(user_lib, recursive = TRUE, showWarnings = FALSE)
  .libPaths(c(user_lib, .libPaths()))
}

packages <- c("mlr3", "mlr3learners", "mlr3pipelines", "mlr3tuning", "mlr3filters",
              "mlr3fselect", "mlr3viz", "mlr3measures", "paradox", "bbotk",
              "ranger", "rpart", "xgboost", "e1071", "kknn", "glmnet",
              "FSelectorRcpp", "smotefamily", "precrec", "iml", "callr",
              "data.table", "ggplot2", "lgr")
missing <- setdiff(packages, rownames(installed.packages()))
if (length(missing) > 0) install.packages(missing)
missing <- setdiff(packages, rownames(installed.packages()))
if (length(missing) > 0) stop("Not installed: ", paste(missing, collapse = ", "))

# Short test: cross-validation of a random forest on a data set shipped with mlr3.
suppressPackageStartupMessages({library(mlr3); library(mlr3learners)})
lgr::get_logger("mlr3")$set_threshold("warn")
rr <- resample(tsk("sonar"), lrn("classif.ranger", num.threads = 1), rsmp("cv", folds = 3))
cat(sprintf("Test passed: MCC on the sonar data = %.2f\n", rr$aggregate(msr("classif.mcc"))))
cat("R", as.character(getRversion()), "| mlr3", as.character(packageVersion("mlr3")), "\n")
