### Install SDMtune Development Version Source: https://github.com/consbiol-unibern/sdmtune/blob/master/README.md Installs the development version of the SDMtune package from GitHub. ```r devtools::install_github("ConsBiol-unibern/SDMtune") ``` -------------------------------- ### Check MaxEnt Installation Source: https://github.com/consbiol-unibern/sdmtune/blob/master/README.md Verifies that the Java JDK is installed, the rJava package is available, and the maxent.jar file is in the correct location for dismo. ```r checkMaxentInstallation() ``` -------------------------------- ### Install SDMtune Package Source: https://github.com/consbiol-unibern/sdmtune/blob/master/README.md Installs the latest release version of the SDMtune package from CRAN. ```r install.packages("SDMtune") ``` -------------------------------- ### Check Maxent Installation Verbose Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/checkMaxentInstallation.md Use this function to check if Maxent is installed correctly with verbose output. It verifies Java, rJava package, and the maxent.jar file. ```R checkMaxentInstallation(verbose = TRUE) ``` -------------------------------- ### SDMmodel Show Output (Maxent, Continuous & Categorical Variables) Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/SDMmodel-class.md Displays the summary of an SDMmodel object configured with the Maxent method, including continuous and categorical variables. This output is useful for verifying model setup before training or analysis. ```R m Message -- Object of class: -- Method: Maxent -- Hyperparameters * fc: "lqph" * reg: 1 * iter: 500 -- Info * Species: Virtual species * Presence locations: 400 * Absence locations: 5000 -- Variables * Continuous: "bio1", "bio12", "bio16", "bio17", "bio5", "bio6", "bio7", and "bio8" * Categorical: "biome" ``` -------------------------------- ### Locate dismo MaxEnt JAR File Source: https://github.com/consbiol-unibern/sdmtune/blob/master/README.md Returns the file path to the MaxEnt JAR file used by the dismo package. Useful for verifying installation or manual upgrades. ```r system.file(package="dismo") ``` -------------------------------- ### Get Method for BM Maxnet CV Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/utils.md Retrieves the method name for the `bm_maxnet_cv` model. ```R .get_method(SDMtune:::bm_maxnet_cv) ``` -------------------------------- ### Check dismo MaxEnt Version Source: https://github.com/consbiol-unibern/sdmtune/blob/master/README.md Prints the version of the MaxEnt implementation used by the dismo package. Requires the dismo package to be installed. ```r dismo::maxent() ``` -------------------------------- ### Get Method for BM Maxnet Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/utils.md Retrieves the method name for the `bm_maxnet` model. ```R .get_method(SDMtune:::bm_maxnet) ``` -------------------------------- ### Get Method for ANN Model Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/utils.md Retrieves the method name for an Artificial Neural Networks model. ```R .get_method(m) ``` -------------------------------- ### Train Maxent model Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Trains a Maxent model, which requires Java, rJava, and maxent.jar to be installed. It allows for custom feature classes and regularization. ```r # Maxent (requires Java + rJava + maxent.jar) maxent_model <- train(method = "Maxent", data = train, fc = "lqph", reg = 1.0, iter = 700) ``` -------------------------------- ### Get Method for BM Maxent Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/utils.md Retrieves the method name for the `bm_maxent` model. ```R .get_method(SDMtune:::bm_maxent) ``` -------------------------------- ### prepareSWD() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Creates an SWD (Samples With Data) object from species coordinates and environmental variables. It handles NA values and converts categorical variables. ```APIDOC ## prepareSWD() — Create a Samples-With-Data object Creates an `SWD` object from species coordinates and a `terra::SpatRaster` of environmental variables. Locations with `NA` values for any predictor are automatically discarded with a warning. Categorical variables are converted to factors. ### Method ```r prepareSWD(species, p, a, env, categorical, ...) ``` ### Parameters - **species** (character) - Name of the species. - **p** (data.frame) - Presence locations with columns X and Y. - **a** (data.frame) - Absence/background locations with columns X and Y. - **env** (terra::SpatRaster) - Stack of environmental variables. - **categorical** (character, optional) - Names of categorical variables. ### Request Example ```r library(SDMtune) # Load environmental rasters (using dismo example data) files <- list.files(path = file.path(system.file(package = "dismo"), "ex"), pattern = "grd", full.names = TRUE) predictors <- terra::rast(files) # Use the built-in virtual species dataset p_coords <- virtualSp$presence # data.frame with columns X, Y bg_coords <- virtualSp$background # data.frame with columns X, Y # Create SWD object — "biome" is treated as a categorical predictor data <- prepareSWD(species = "Virtual species", p = p_coords, a = bg_coords, env = predictors, categorical = "biome") data ``` ### Response Returns an `SWD` object containing species data and environmental variables. ``` -------------------------------- ### SDMmodel Show Output (Maxnet, Continuous & Categorical Variables) Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/SDMmodel-class.md Illustrates the summary of an SDMmodel object using the Maxnet algorithm, including both continuous and categorical variables. This output is relevant for models employing the Maxnet method. ```R m Message -- Object of class: -- Method: Maxnet -- Hyperparameters * fc: "lqph" * reg: 1 -- Info * Species: Virtual species * Presence locations: 400 * Absence locations: 5000 -- Variables * Continuous: "bio1", "bio12", "bio16", "bio17", "bio5", "bio6", "bio7", and "bio8" * Categorical: "biome" ``` -------------------------------- ### SDMmodelCV Show Output - Maxnet with Continuous and Categorical Variables Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/SDMmodelCV-class.md Presents the output of the show method for an SDMmodelCV object using the Maxnet method, detailing hyperparameters, species info, and both continuous and categorical variables. ```text -- Object of class: -- Method: Maxnet -- Hyperparameters * fc: "lqph" * reg: 1 -- Info * Species: Virtual species * Replicates: 4 * Total presence locations: 400 * Total absence locations: 5000 -- Variables * Continuous: "bio1", "bio12", "bio16", "bio17", "bio5", "bio6", "bio7", and "bio8" * Categorical: "biome" ``` -------------------------------- ### Prepare SWD object with prepareSWD() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Creates an SWD object from species coordinates and environmental rasters. Handles categorical variables and automatically discards locations with NA values. ```R library(SDMtune) # Load environmental rasters (using dismo example data) files <- list.files(path = file.path(system.file(package = "dismo"), "ex"), pattern = "grd", full.names = TRUE) predictors <- terra::rast(files) # Use the built-in virtual species dataset p_coords <- virtualSp$presence # data.frame with columns X, Y bg_coords <- virtualSp$background # data.frame with columns X, Y # Create SWD object — "biome" is treated as a categorical predictor data <- prepareSWD(species = "Virtual species", p = p_coords, a = bg_coords, env = predictors, categorical = "biome") data # ── Virtual species ────────────────────────────────────────────────────────── # Presence locations : 200 # Absence/Background: 10000 # Variables: bio1 bio2 bio3 bio4 bio5 bio6 bio7 bio8 bio9 biome ``` -------------------------------- ### Display Maxnet Object Details Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/Maxnet-class.md Shows the output of the `show` method for a Maxnet object, detailing its class, method, and hyperparameters. ```text -- Object of class: -- Method: Maxnet -- Hyperparameters * reg: 1 * fc: "lqph" ``` -------------------------------- ### Benchmark Prediction Speed: SDMtune vs dismo Source: https://github.com/consbiol-unibern/sdmtune/blob/master/README.md Uses the microbenchmark package to compare the execution time of the predict function between SDMtune and dismo for Maxent models. Requires pre-defined 'sdmtune_model', 'data', and 'my_check'. ```r bench <- microbenchmark::microbenchmark( SDMtune = predict(sdmtune_model, data = data, type = "cloglog"), dismo = predict(maxent_model, data@data), check = my_check ) ``` -------------------------------- ### Hyperparameter Tuning with Grid Search and Optimize Model Source: https://github.com/consbiol-unibern/sdmtune/blob/master/README.md Compares gridSearch and optimizeModel for hyperparameter tuning using a Maxnet model. Demonstrates data preparation, model training, and evaluation with AUC. The gridSearch function tests all combinations, while optimizeModel uses a genetic algorithm for potentially faster optimization. Results are ordered by test AUC. ```r library(SDMtune) # Acquire environmental variables files <- list.files(path = file.path(system.file(package = "dismo")), pattern = "grd", full.names = TRUE) predictors <- terra::rast(files) # Prepare presence and background locations p_coords <- virtualSp$presence bg_coords <- virtualSp$background # Create SWD object data <- prepareSWD(species = "Virtual species", p = p_coords, a = bg_coords, env = predictors, categorical = "biome") # Split presence locations in training (80%) and testing (20%) datasets datasets <- trainValTest(data, test = 0.2, only_presence = TRUE, seed = 25) train <- datasets[[1]] test <- datasets[[2]] # Train a Maxnet model model <- train(method = "Maxnet", data = train) # Define the hyperparameters to test h <- list(reg = seq(0.1, 3, 0.1), fc = c("lq", "lh", "lqp", "lqph", "lqpht")) # Test all the possible combinations with gridSearch gs <- gridSearch(model, hypers = h, metric = "auc", test = test) head(gs@results[order(-gs@results$test_AUC), ]) # Best combinations # Use the genetic algorithm instead with optimizeModel om <- optimizeModel(model, hypers = h, metric = "auc", test = test, seed = 4) head(om@results) # Best combinations ``` -------------------------------- ### Display BRT Object Details Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/BRT-class.md Shows the detailed output of the `show` method for a BRT object, including its class, method, and hyperparameters. ```R m@model Message -- Object of class: -- Method: Boosted Regression Trees -- Hyperparameters * distribution: "bernoulli" * n.trees: 200 * interaction.depth: 1 * shrinkage: 0.2 * bag.fraction: 0.6 ``` -------------------------------- ### Add presences to background with addSamplesToBg() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Replicates Maxent's addsamplestobackground behavior by appending presence locations to the background set if their environmental profiles are not already represented. Can also add all presence locations regardless of duplication. ```R # Append unique presence environmental profiles to background data_with_pres_in_bg <- addSamplesToBg(data) # Add ALL presence locations regardless of duplication (addallsamplestobackground) data_all_in_bg <- addSamplesToBg(data, all = TRUE) ``` -------------------------------- ### Create k-fold CV partitions with randomFolds() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Generates logical training/testing matrices for k-fold cross-validation. Compatible with outputs from ENMeval and blockCV packages. Presence-only locations are split, while background locations are included in every fold. ```R # 4-fold CV: only presence locations are split; all background in every fold fold <- randomFolds(data, k = 4, only_presence = TRUE, seed = 123) # folds$train and folds$test are logical matrices with k columns ``` -------------------------------- ### SWD Show Method Output with Only Categorical Variables Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/SWD-class.md Illustrates the output of the SWD show method when only categorical variables are present. The continuous variable section will indicate 'NA'. ```text -- Object of class: -- -- Info * Species: Virtual species * Presence locations: 400 * Absence locations: 5000 -- Variables * Continuous: NA * Categorical: "biome" ``` -------------------------------- ### SWD Show Method Output with Continuous and Categorical Variables Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/SWD-class.md Displays the output of the SWD show method when both continuous and categorical variables are present. This output includes species information, location counts, and lists of both variable types. ```text -- Object of class: -- -- Info * Species: Virtual species * Presence locations: 400 * Absence locations: 5000 -- Variables * Continuous: "bio1", "bio12", "bio16", "bio17", "bio5", "bio6", "bio7", and * Categorical: "biome" ``` -------------------------------- ### Maxent Class Show Output Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/Maxent-class.md Displays the configuration and hyperparameters of a Maxent object. This output is generated when the show method is called on a Maxent object. ```text -- Object of class: -- Method: Maxent -- Hyperparameters * reg: 1 * fc: "lqph" * iter: 500 ``` -------------------------------- ### SDMmodelCV Show Output - Maxent with Continuous and Categorical Variables Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/SDMmodelCV-class.md Displays the output of the show method for an SDMmodelCV object using the Maxent method, detailing hyperparameters, species info, and both continuous and categorical variables. ```text -- Object of class: -- Method: Maxent -- Hyperparameters * fc: "lqph" * reg: 1 * iter: 500 -- Info * Species: Virtual species * Replicates: 4 * Total presence locations: 400 * Total absence locations: 5000 -- Variables * Continuous: "bio1", "bio12", "bio16", "bio17", "bio5", "bio6", "bio7", and "bio8" * Categorical: "biome" ``` -------------------------------- ### SWD Show Method Output with Only Continuous Variables Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/SWD-class.md Shows the output of the SWD show method when only continuous variables are defined. The categorical variable section will indicate 'NA'. ```text -- Object of class: -- -- Info * Species: Virtual species * Presence locations: 400 * Absence locations: 5000 -- Variables * Continuous: "bio1", "bio12", and "bio16" * Categorical: NA ``` -------------------------------- ### SDMmodelCV Show Output - Maxent with Only Continuous Variables Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/SDMmodelCV-class.md Shows the output of the show method for an SDMmodelCV object using Maxent, where only continuous variables are specified. ```text -- Object of class: -- Method: Maxent -- Hyperparameters * fc: "lqph" * reg: 1 * iter: 500 -- Info * Species: Virtual species * Replicates: 4 * Total presence locations: 400 * Total absence locations: 5000 -- Variables * Continuous: "bio1", "bio12", and "bio16" * Categorical: NA ``` -------------------------------- ### addSamplesToBg() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Replicates Maxent's `addsamplestobackground` behavior by adding presence locations to the background set if their environmental profiles are not already represented. ```APIDOC ## addSamplesToBg() — Add presences to background Replicates the Maxent `addsamplestobackground` behaviour by appending presence locations (those whose environmental values are not already represented in the background) to the background set. ### Method ```r addSamplesToBg(data, all = FALSE, ...) ``` ### Parameters - **data** (SWD) - An `SWD` object. - **all** (logical, optional) - If TRUE, all presence locations are added, regardless of duplication. Defaults to FALSE. ### Request Example ```r # Append unique presence environmental profiles to background data_with_pres_in_bg <- addSamplesToBg(data) # Add ALL presence locations regardless of duplication (addallsamplestobackground) data_all_in_bg <- addSamplesToBg(data, all = TRUE) ``` ### Response Returns an `SWD` object with presence locations potentially added to the background set. ``` -------------------------------- ### SDMmodelCV Show Output - Maxent with Only Categorical Variables Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/SDMmodelCV-class.md Illustrates the output of the show method for an SDMmodelCV object using Maxent, when only categorical variables are included. ```text -- Object of class: -- Method: Maxent -- Hyperparameters * fc: "lqph" * reg: 1 * iter: 500 -- Info * Species: Virtual species * Replicates: 4 * Total presence locations: 400 * Total absence locations: 5000 -- Variables * Continuous: NA * Categorical: "biome" ``` -------------------------------- ### ANN Class Show Method Output Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/ANN-class.md Displays the details of an ANN model object, including its method, hyperparameters, size, decay, rang, and maxit. ```text m@model Message -- Object of class: -- Method: Artificial Neural Networks -- Hyperparameters * size: 10 * decay: 0 * rang: 0.7 * maxit: 100 ``` -------------------------------- ### RF Class Show Method Output Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/RF-class.md Displays the summary output of an RF model object. This output includes the class type, method used, and a list of hyperparameters such as mtry, ntree, and nodesize. ```text -- Object of class: -- Method: Random Forest -- Hyperparameters * mtry: 2 * ntree: 200 * nodesize: 1 ``` -------------------------------- ### train() — Train a species distribution model Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Trains a single SDMmodel or a cross-validated SDMmodelCV for one or more algorithm families. Extra hyperparameter arguments are forwarded to the underlying algorithm. ```APIDOC ## train() ### Description Trains a single `SDMmodel` or a cross-validated `SDMmodelCV` for one or more algorithm families. Extra hyperparameter arguments are forwarded to the underlying algorithm. ### Method `train(method, data, ...)` ### Parameters - **method** (character or vector) - The algorithm(s) to use (e.g., "Maxnet", "RF"). - **data** (data.frame or similar) - The input data for training. - **fc** (character) - Feature class(es) to use (e.g., "l", "lq"). - **folds** (list) - Pre-defined cross-validation folds. - **reg** (numeric) - Regularization parameter (for Maxent/Maxnet). - **iter** (numeric) - Number of iterations (for Maxent). - **ntree** (numeric) - Number of trees (for RF). - **n.trees** (numeric) - Number of boosting trees (for BRT). - **shrinkage** (numeric) - Shrinkage parameter (for BRT). - **size** (numeric) - Number of nodes (for ANN). - **decay** (numeric) - Weight decay parameter (for ANN). ### Request Example ```r # Single model maxnet_model <- train(method = "Maxnet", data = train, fc = "lq", reg = 1.5) # Cross-validated model # folds <- randomFolds(data, k = 4) # cv_model <- train(method = "Maxnet", data = data, fc = "lq", folds = folds) ``` ### Response Returns an `SDMmodel` or `SDMmodelCV` object. ``` -------------------------------- ### Train Maxent Model with SDMtune Source: https://github.com/consbiol-unibern/sdmtune/blob/master/README.md Trains a Maxent model using the SDMtune package. Requires the 'data' object to be pre-defined. ```r sdmtune_model <- train(method = "Maxent", data = data) ``` -------------------------------- ### optimizeModel() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Optimizes model hyperparameters using a genetic algorithm to explore the hyperparameter space and find optimal configurations. ```APIDOC ## optimizeModel() ### Description Uses a genetic algorithm (selection + crossover + mutation) to efficiently explore a large hyperparameter space and converge toward an optimal configuration. ### Parameters - `maxnet_model`: The model object to optimize. - `hypers`: A list of hyperparameter ranges to explore. - `metric`: The evaluation metric to optimize (e.g., "auc"). - `test`: The validation dataset. - `pop`: Population size per generation. - `gen`: Number of generations. - `keep_best`: Proportion of top individuals to keep. - `keep_random`: Proportion of random individuals to keep. - `mutation_chance`: Probability of mutation. - `seed`: Random seed for reproducibility. ### Returns An object containing optimization results, including evaluated combinations and the best model. ### Example ```r h <- list(reg = seq(0.2, 5, 0.2), fc = c("l", "lq", "lh", "lp", "lqp", "lqph")) om <- optimizeModel(maxnet_model, hypers = h, metric = "auc", test = val, pop = 20, gen = 5, keep_best = 0.4, keep_random = 0.2, mutation_chance = 0.4, seed = 123) om@results # data frame of all evaluated combinations om@models[[1]] # best model ``` ``` -------------------------------- ### SDMmodel Show Output (Maxent, Only Continuous Variables) Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/SDMmodel-class.md Shows the summary of an SDMmodel object using the Maxent method with only continuous variables specified. This output is helpful for checking models that do not incorporate categorical predictors. ```R m Message -- Object of class: -- Method: Maxent -- Hyperparameters * fc: "lqph" * reg: 1 * iter: 500 -- Info * Species: Virtual species * Presence locations: 400 * Absence locations: 5000 -- Variables * Continuous: "bio1", "bio12", and "bio16" * Categorical: NA ``` -------------------------------- ### Train SDM with Maxnet and custom features Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Trains a Maxnet model with a specified feature class ('lq') and regularization value. This is useful for fine-tuning Maxnet models. ```r # Maxnet with custom feature class and regularization maxnet_model <- train(method = "Maxnet", data = train, fc = "lq", reg = 1.5) ``` -------------------------------- ### Train Boosted Regression Trees model Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Trains a Boosted Regression Trees (BRT) model with specified number of trees and shrinkage. BRT is effective for capturing complex interactions. ```r # Boosted Regression Trees brt_model <- train(method = "BRT", data = train, n.trees = 200, shrinkage = 0.05) ``` -------------------------------- ### Optimize Model Hyperparameters with Genetic Algorithm Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Uses a genetic algorithm to explore hyperparameter space for optimal model configuration. Specify the hyperparameter list, metric, test data, and genetic algorithm parameters. ```r h <- list(reg = seq(0.2, 5, 0.2), fc = c("l", "lq", "lh", "lp", "lqp", "lqph")) om <- optimizeModel(maxnet_model, hypers = h, metric = "auc", test = val, pop = 20, # population size per generation gen = 5, # number of generations keep_best = 0.4, # top 40% survive keep_random = 0.2, # additional 20% random survivors mutation_chance = 0.4, seed = 123) om@results # data frame of all evaluated combinations om@models[[1]] # best model ``` -------------------------------- ### SDMmodel Show Output (Maxent, Only Categorical Variables) Source: https://github.com/consbiol-unibern/sdmtune/blob/master/tests/testthat/_snaps/SDMmodel-class.md Presents the summary of an SDMmodel object with the Maxent method, specifying only categorical variables. This output is useful for models that exclusively use categorical predictors. ```R m Message -- Object of class: -- Method: Maxent -- Hyperparameters * fc: "lqph" * reg: 1 * iter: 500 -- Info * Species: Virtual species * Presence locations: 400 * Absence locations: 5000 -- Variables * Continuous: NA * Categorical: "biome" ``` -------------------------------- ### Train multiple SDM methods simultaneously Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Trains multiple SDM algorithms at once and returns them as a named list. This is useful for comparing different model types. ```r # Train multiple methods at once — returns a named list all_models <- train(method = c("Maxnet", "RF", "BRT"), data = train, fc = "lq", ntree = 300, n.trees = 200) all_models$Maxnet all_models$RF ``` -------------------------------- ### trainValTest() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Randomly splits an SWD object into training, validation, and testing subsets, optionally preserving the presence-to-absence ratio. ```APIDOC ## trainValTest() — Split data into train / validation / test partitions Randomly splits an `SWD` object into two or three subsets while optionally preserving the presence-to-absence ratio. When `only_presence = TRUE` (common for presence-background methods), background locations are included in every partition. ### Method ```r trainValTest(data, test = 0, val = 0, only_presence = FALSE, seed = NULL, ...) ``` ### Parameters - **data** (SWD) - An `SWD` object. - **test** (numeric, optional) - Proportion of data to use for the test set. Defaults to 0. - **val** (numeric, optional) - Proportion of data to use for the validation set. Defaults to 0. - **only_presence** (logical, optional) - If TRUE, only presence locations are split. Defaults to FALSE. - **seed** (integer, optional) - Random seed for reproducibility. ### Request Example ```r # Two-way split: 80% train, 20% test (presence only split) sets_2 <- trainValTest(data, test = 0.2, only_presence = TRUE, seed = 42) train <- sets_2[[1]] test <- sets_2[[2]] # Three-way split: 60% train, 20% val, 20% test (stratified) sets_3 <- trainValTest(data, val = 0.2, test = 0.2, seed = 42) train <- sets_3[[1]] val <- sets_3[[2]] test <- sets_3[[3]] ``` ### Response Returns a list of data subsets (train, validation, test) as `SWD` objects. ``` -------------------------------- ### randomFolds() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Generates k-fold cross-validation partitions for an SWD object, compatible with ENMeval and blockCV packages. ```APIDOC ## randomFolds() — Create k-fold cross-validation partitions Generates a list of logical training/testing matrices for k-fold cross-validation. Compatible output is also accepted from **ENMeval** and **blockCV** packages. ### Method ```r randomFolds(data, k, only_presence = FALSE, seed = NULL, ...) ``` ### Parameters - **data** (SWD) - An `SWD` object. - **k** (integer) - The number of folds for cross-validation. - **only_presence** (logical, optional) - If TRUE, only presence locations are split. Defaults to FALSE. - **seed** (integer, optional) - Random seed for reproducibility. ### Request Example ```r # 4-fold CV: only presence locations are split; all background in every fold folds <- randomFolds(data, k = 4, only_presence = TRUE, seed = 123) # folds$train and folds$test are logical matrices with k columns ``` ### Response Returns a list containing logical matrices for training and testing folds. ``` -------------------------------- ### Split data with trainValTest() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Randomly splits an SWD object into training, validation, and/or test subsets. Can preserve the presence-to-absence ratio and optionally include background locations in all partitions. ```R # Two-way split: 80% train, 20% test (presence only split) sets_2 <- trainValTest(data, test = 0.2, only_presence = TRUE, seed = 42) train <- sets_2[[1]] test <- sets_2[[2]] # Three-way split: 60% train, 20% val, 20% test (stratified) sets_3 <- trainValTest(data, val = 0.2, test = 0.2, seed = 42) train <- sets_3[[1]] val <- sets_3[[2]] test <- sets_3[[3]] ``` -------------------------------- ### Plot Benchmark Results Source: https://github.com/consbiol-unibern/sdmtune/blob/master/README.md Generates a boxplot of the benchmark results using ggplot2, visualizing the time taken by SDMtune and dismo for predictions. Requires the 'bench' object from the previous step. ```r library(ggplot2) ggplot(bench, aes(x = expr, y = time/1000000, fill = expr)) + geom_boxplot() + labs(fill = "", x = "Package", y = "time (milliseconds)") + theme_minimal() ``` -------------------------------- ### plotResponse() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Generates plots of environmental response curves for model variables. ```APIDOC ## plotResponse() ### Description Returns a `ggplot2` object showing how predicted habitat suitability changes along a variable's range. Both univariate ("with only") and marginal curves (all other variables held at their mean/mode) are supported. Works with both `SDMmodel` and `SDMmodelCV` (shows mean ± SD ribbon). ### Parameters - `model`: The model object (`SDMmodel` or `SDMmodelCV`). - `var`: The variable name for which to plot the response curve. - `type`: The type of response curve to plot (e.g., "cloglog", "logistic"). - `marginal`: If TRUE, plots marginal response curves. - `rug`: If TRUE, adds rug ticks to the plot. - `color`: Custom color for the response curve. ### Returns A `ggplot2` object representing the response curve plot. ### Example ```r # Univariate cloglog response for bio1 plotResponse(maxnet_model, var = "bio1", type = "cloglog") # Marginal response with rug ticks and custom color plotResponse(maxnet_model, var = "bio12", type = "logistic", marginal = TRUE, rug = TRUE, color = "steelblue") ``` ``` -------------------------------- ### Train Random Forest model Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Trains a Random Forest model with a specified number of trees. This is a common and robust algorithm for SDMs. ```r # Random Forest rf_model <- train(method = "RF", data = train, ntree = 500) ``` -------------------------------- ### Train Artificial Neural Network model Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Trains an Artificial Neural Network (ANN) model with specified network size and decay parameter. ANNs can capture non-linear relationships. ```r # ANN ann_model <- train(method = "ANN", data = train, size = 15, decay = 0.1) ``` -------------------------------- ### Generate HTML Model Report Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Creates a comprehensive HTML report for a trained model, optionally including ROC curves, variable importance, Jackknife plots, response curves, and prediction maps. Requires predictor variables and specifies permutation test details. ```r modelReport(maxnet_model, folder = "my_report", test = test, type = "cloglog", response_curves = TRUE, only_presence = TRUE, jk = TRUE, env = predictors, permut = 5) ``` -------------------------------- ### Random Search for hyperparameters Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Performs a random search over hyperparameter combinations, which is faster than grid search for large parameter spaces. It samples a population of combinations and evaluates them. ```r h <- list(reg = seq(0.1, 5, 0.1), fc = c("l", "lq", "lh", "lqp", "lqph", "lqpht")) rs <- randomSearch(maxnet_model, hypers = h, metric = "auc", test = test, pop = 15, seed = 42) rs@results[order(-rs@results$test_AUC), ] rs@models[[1]] # Best model from the random search ``` -------------------------------- ### modelReport() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Generates a full HTML model report, including optional components like ROC curves, variable importance, and response curves. ```APIDOC ## modelReport() ### Description Produces a self-contained HTML report analogous to MaxEnt's built-in report. Optionally includes ROC curve, variable importance table, Jackknife test plots, response curves, and a prediction map. ### Parameters - **maxnet_model**: The trained SDM model object. - **folder** (string, optional): The directory to save the report and associated files. Defaults to "my_report". - **test** (optional): Test data for generating ROC curves. - **type** (string, optional): The type of transformation to use for response curves. Defaults to "cloglog". - **response_curves** (boolean, optional): Whether to include response curves in the report. Defaults to TRUE. - **only_presence** (boolean, optional): Whether to only consider presence data for certain plots. Defaults to TRUE. - **jk** (boolean, optional): Whether to include Jackknife test plots. Defaults to TRUE. - **env** (optional): Environmental predictor layers, required if `response_curves` is TRUE and not already part of the model object. - **permut** (integer, optional): Number of permutations for the Jackknife test. Defaults to 5. ### Usage Example ```r modelReport(maxnet_model, folder = "my_report", test = test, type = "cloglog", response_curves = TRUE, only_presence = TRUE, jk = TRUE, env = predictors, permut = 5) ``` ### Output - Opens `my_report/virtual_species.html` in the default browser. - Saves `model.Rds`, `train.csv`, `test.csv`, and plot PNGs under `my_report/plots/`. ``` -------------------------------- ### gridSearch() — Exhaustive hyperparameter grid search Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Performs an exhaustive grid search over specified hyperparameter combinations to find the best model. ```APIDOC ## gridSearch() ### Description Performs an exhaustive grid search over supplied hyperparameter values, training a model for each combination and ranking them by a chosen metric. An interactive chart is shown in the RStudio Viewer. ### Method `gridSearch(object, hypers, metric, ...)` ### Parameters - **object** (SDMmodel) - The base model object to tune. - **hypers** (list) - A list where each element is a named vector of hyperparameter values to search. - **metric** (character) - The metric to use for ranking models (e.g., "auc", "aicc"). - **test** (data.frame) - Optional test data for evaluating models. - **env** (SpatRaster or similar) - Environmental variables (required for AICc). - **save_models** (logical) - Whether to save all trained models (can consume significant memory). ### Request Example ```r # Define hyperparameter grid # h <- list(reg = seq(0.5, 3, 0.5), fc = c("l", "lq")) # Perform grid search # gs <- gridSearch(maxnet_model, hypers = h, metric = "auc", test = test) # Get best model # best_model <- gs@models[[which.max(gs@results$test_AUC)]] ``` ### Response Returns a `gridSearch` object containing results and potentially models. ``` -------------------------------- ### Grid Search for hyperparameters Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Performs an exhaustive grid search over specified hyperparameter combinations to find the optimal settings for a model, evaluated by a chosen metric (e.g., AUC) on a test set. ```r # Define hyperparameter grid h <- list(reg = seq(0.5, 3, 0.5), fc = c("l", "lq", "lqp", "lqph")) # Grid search using AUC on a held-out test set gs <- gridSearch(maxnet_model, hypers = h, metric = "auc", test = test) # Inspect results sorted by test AUC (descending) gs@results[order(-gs@results$test_AUC), ] # reg fc train_AUC test_AUC # 3 0.5 lqp 0.9812 0.9601 # ... # Best model gs@models[[which.max(gs@results$test_AUC)]] ``` -------------------------------- ### Memory-efficient Grid Search Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Performs a grid search without saving all intermediate models, which is useful for very large hyperparameter grids to conserve memory. Evaluation is still performed. ```r # Memory-efficient mode (large grids): skip saving all models gs2 <- gridSearch(maxnet_model, hypers = h, metric = "aicc", env = predictors, save_models = FALSE) ``` -------------------------------- ### Convert SDMtune Model to dismo MaxEnt Source: https://github.com/consbiol-unibern/sdmtune/blob/master/README.md Converts an SDMtune Maxent model object to a format compatible with the dismo package. This is necessary for direct comparison of prediction functions. ```r maxent_model <- SDMmodel2MaxEnt(sdmtune_model) ``` -------------------------------- ### predict() — Generate model predictions Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Dispatches to the underlying algorithm and returns model predictions. ```APIDOC ## predict() ### Description Generates model predictions on new data. Can return a numeric vector for tabular data or a `terra::SpatRaster` for raster data. The output type can be specified for Maxent/Maxnet models. ### Method `predict(object, data, ...)` ### Parameters - **object** (SDMmodel) - The trained model object. - **data** (data.frame or SpatRaster) - The input data for prediction. - **type** (character) - The type of output prediction (e.g., "cloglog", "logistic", "raw", "link", "exponential"). - **filename** (character) - Path to save the prediction raster. - **extent** (terra::ext or similar) - Spatial extent to restrict predictions. ### Request Example ```r # Predict on tabular data # pred_vec <- predict(maxnet_model, data = test, type = "cloglog") # Predict on raster data # pred_raster <- predict(maxnet_model, data = predictors, type = "logistic") # Save prediction to file # predict(maxnet_model, data = predictors, type = "cloglog", filename = "prediction.tif") ``` ### Response Returns a numeric vector or a `terra::SpatRaster` containing predictions. ``` -------------------------------- ### varImp() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Calculates permutation-based variable importance by measuring the decrease in a chosen metric when a variable is permuted. ```APIDOC ## varImp() ### Description Permutes each variable in turn and measures the resulting decrease in training AUC. Returns a ranked data frame of permutation importances normalized to percentages. ### Parameters - `model`: The model object (e.g., `maxnet_model` or `cv_model`). - `permut`: Number of permutations to perform for each variable. ### Returns A data frame with variable importance scores and their standard deviations. ### Example ```r vi <- varImp(maxnet_model, permut = 10) vi # Variable Permutation_importance sd # 1 bio5 42.1 0.021 # 2 bio12 28.7 0.018 # ... # For cross-validated models: mean ± sd across folds vi_cv <- varImp(cv_model, permut = 5) ``` ``` -------------------------------- ### Plot Environmental Response Curves Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Generates a ggplot2 object showing habitat suitability changes along a variable's range. Supports univariate and marginal curves, and works with both `SDMmodel` and `SDMmodelCV` (showing mean ± SD ribbon). ```r # Univariate cloglog response for bio1 plotResponse(maxnet_model, var = "bio1", type = "cloglog") # Marginal response with rug ticks and custom color plotResponse(maxnet_model, var = "bio12", type = "logistic", marginal = TRUE, rug = TRUE, color = "steelblue") ``` -------------------------------- ### tss() — Compute True Skill Statistic Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Calculates the True Skill Statistic (TSS) to evaluate model performance. ```APIDOC ## tss() ### Description Calculates the True Skill Statistic (TSS), which measures the agreement between predicted and observed occurrences. Supports both single models and cross-validated models. ### Method `tss(object, test = NULL, ...)` ### Parameters - **object** (SDMmodel or SDMmodelCV) - The trained model object. - **test** (data.frame or logical) - Optional test data or a flag indicating to use cross-validation test results. ### Request Example ```r # Training TSS # tss_train <- tss(maxnet_model) # Testing TSS # tss_test <- tss(maxnet_model, test = test) # CV mean TSS # tss_cv <- tss(cv_model, test = TRUE) ``` ### Response Returns a numeric value representing the TSS. ``` -------------------------------- ### randomSearch() — Random hyperparameter search Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Performs a random search over hyperparameter combinations, sampling a subset of possibilities. ```APIDOC ## randomSearch() ### Description Randomly samples hyperparameter combinations from a defined grid, offering a faster alternative to exhaustive grid search for large hyperparameter spaces. ### Method `randomSearch(object, hypers, metric, ...)` ### Parameters - **object** (SDMmodel) - The base model object to tune. - **hypers** (list) - A list where each element is a named vector of hyperparameter values to sample from. - **metric** (character) - The metric to use for ranking models (e.g., "auc"). - **test** (data.frame) - Optional test data for evaluating models. - **pop** (numeric) - The number of hyperparameter combinations to sample. - **seed** (numeric) - A random seed for reproducibility. ### Request Example ```r # Define hyperparameter space # h <- list(reg = seq(0.1, 5, 0.1), fc = c("l", "lqph")) # Perform random search # rs <- randomSearch(maxnet_model, hypers = h, metric = "auc", test = test, pop = 15, seed = 42) # Get best model # best_model_rs <- rs@models[[which.max(rs@results$test_AUC)]] ``` ### Response Returns a `randomSearch` object containing results and potentially models. ``` -------------------------------- ### Thin data with thinData() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Removes spatial duplicates and locations with NA environmental values. Can accept data frames with custom column names for coordinates. ```R # Sample background locations (some may fall on NA cells) bg_raw <- terra::spatSample(predictors, size = 9000, method = "random", xy = TRUE, values = FALSE) # Thin: keep one location per cell, discard NA cells thinned_bg <- thinData(bg_raw, env = predictors) # ✔ Removed 0 NAs and 312 duplicated locations # Custom column names age <- sample(1:3, nrow(bg_raw), replace = TRUE) df <- cbind(age = age, X = bg_raw$x, Y = bg_raw$y) thinned_df <- thinData(df, env = predictors, x = "X", y = "Y") ``` -------------------------------- ### doJk() Source: https://context7.com/consbiol-unibern/sdmtune/llms.txt Performs a Jackknife test for variable importance by training models with each variable removed or in isolation. ```APIDOC ## doJk() ### Description Trains models with each variable removed ("without") and each variable in isolation ("with only"), reporting the metric for each. Can return all retrained models for downstream use. ### Parameters - `model`: The model object. - `metric`: The evaluation metric to use (e.g., "auc"). - `variables`: A character vector of variable names to test. - `test`: The validation dataset. - `with_only`: If TRUE, also trains models with only one variable. - `return_models`: If TRUE, returns the retrained models. ### Returns A list containing results and optionally retrained models. ### Example ```r # Jackknife with AUC, for specific variables jk <- doJk(maxnet_model, metric = "auc", variables = c("bio1", "bio5", "bio12"), test = test, with_only = TRUE) jk # Variable Train_AUC_without Train_AUC_withonly Test_AUC_without Test_AUC_withonly # 1 bio1 0.9498 0.8321 0.9312 0.8104 # ... # Return retrained models as well jk_full <- doJk(maxnet_model, metric = "auc", test = test, return_models = TRUE) jk_full$results jk_full$models_without[[1]] # model with first variable removed jk_full$models_withonly[[1]] # model with only first variable ``` ```