### Install nloptr from source Source: https://github.com/astamm/nloptr/blob/master/vignettes/nloptr.Rmd Installs the nloptr package from source using install.packages() with type = "source". ```R install.packages("nloptr", type = "source") ``` -------------------------------- ### auglag example with gradient and Jacobian functions Source: https://github.com/astamm/nloptr/blob/master/man/auglag.Rd Example setup for minimizing a function with inequality and equality constraints. Defines the objective fn, inequality hin (hin <= 0), equality heq (heq = 0), and uses nl.grad and nl.jacobian for gradient and Jacobian computations. ```r x0 <- c(1, 1) fn <- function(x) (x[1] - 2) ^ 2 + (x[2] - 1) ^ 2 hin <- function(x) 0.25 * x[1]^2 + x[2] ^ 2 - 1 # hin <= 0 heq <- function(x) x[1] - 2 * x[2] + 1 # heq = 0 gr <- function(x) nl.grad(x, fn) hinjac <- function(x) nl.jacobian(x, hin) heqjac <- function(x) nl.jacobian(x, heq) ``` -------------------------------- ### Install development version from GitHub Source: https://github.com/astamm/nloptr/blob/master/README.Rmd Use this command to install the development version of nloptr from GitHub. The remotes package is required; uncomment the first line if it is not already installed. ```r # install.packages("remotes") remotes::install_github("astamm/nloptr") ``` -------------------------------- ### Set initial point and bounds for stogo Source: https://github.com/astamm/nloptr/blob/master/man/stogo.Rd Sets the initial point x0 and lower/upper bounds for the stogo optimization example. ```r x0 <- c(-1.2, 1) lb <- c(-3, -3) ub <- c(3, 3) ``` -------------------------------- ### Error handling with non-numeric starting point Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/bobyqa.md Passing a non-numeric starting point like "a" causes nloptr() to reject it before solving, producing the error 'x0 must be numeric'. Use try() to catch the error. ```r library(nloptr) # Non-numeric starting point is rejected by nloptr() before solving: try(bobyqa("a", function(x) sum(x^2))) # -> Error in nloptr(...) : x0 must be numeric ``` -------------------------------- ### Set initial values and options for nloptr Source: https://github.com/astamm/nloptr/blob/master/man/nloptr.Rd Sets the starting point x0 and optimization options, specifying the NLOPT_LD_LBFGS algorithm and a relative tolerance of 1.0e-8. ```R # initial values x0 <- c(-1.2, 1) opts <- list("algorithm"="NLOPT_LD_LBFGS", "xtol_rel"=1.0e-8) ``` -------------------------------- ### Installation Error Message Source: https://github.com/astamm/nloptr/blob/master/revdep/failures.md Shown when the package installation fails during reverse dependency checks. Directs to the detailed installation log file. ```text Installation failed. See ‘/Users/stamm-a/Softs/nloptr/revdep/checks.noindex/spaMM/new/spaMM.Rcheck/00install.out’ for details. ``` -------------------------------- ### Install nloptr from CRAN Source: https://github.com/astamm/nloptr/blob/master/README.Rmd Use this command to install the stable version of the nloptr package from CRAN. ```r install.packages("nloptr") ``` -------------------------------- ### Run bobyqa without bounds Source: https://github.com/astamm/nloptr/blob/master/man/bobyqa.Rd Calls bobyqa with starting point c(0, 0) and the Rosenbrock function. The result is stored in S and then printed. ```r S <- bobyqa(c(0, 0), rbf) ``` ```r S ``` -------------------------------- ### Error handling for non-finite starting point Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/newuoa.md Attempts newuoa with a starting point containing NA, which is rejected by nloptr() with the error 'Error in is.nloptr(ret) : x0 contains NA'. The try() call captures the error. ```r library(nloptr) # Non-finite starting point is rejected by nloptr(): try(newuoa(c(NA, 2), rbf)) # -> Error in is.nloptr(ret) : x0 contains NA ``` -------------------------------- ### Devel Installation Log Source: https://github.com/astamm/nloptr/blob/master/revdep/failures.md Log output from the development version installation showing compilation failure due to missing gsl/gsl_sf_bessel.h header. ```text * installing *source* package ‘spaMM’ ... ** package ‘spaMM’ successfully unpacked and MD5 sums checked ** using staged installation ** libs using C++ compiler: ‘Apple clang version 16.0.0 (clang-1600.0.26.6)’ using SDK: ‘MacOSX15.2.sdk’ clang++ -arch arm64 -std=gnu++17 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/Rcpp/include' -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/RcppEigen/include' -I/opt/R/arm64/include -fPIC -falign-functions=64 -Wall -g -O2 -c COMPoisson.cpp -o COMPoisson.o clang++ -arch arm64 -std=gnu++17 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/Rcpp/include' -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/RcppEigen/include' -I/opt/R/arm64/include -fPIC -falign-functions=64 -Wall -g -O2 -c PLS.cpp -o PLS.o In file included from PLS.cpp:1: In file included from ./spaMM_linear.h:4: ... | ^ 5 warnings generated. clang++ -arch arm64 -std=gnu++17 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/Rcpp/include' -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/RcppEigen/include' -I/opt/R/arm64/include -fPIC -falign-functions=64 -Wall -g -O2 -c newBessel.cpp -o newBessel.o newBessel.cpp:2:10: fatal error: 'gsl/gsl_sf_bessel.h' file not found 2 | #include | ^~~~~~~~~~~~~~~~~~~~~ 1 error generated. make: *** [newBessel.o] Error 1 ERROR: compilation failed for package ‘spaMM’ * removing ‘/Users/stamm-a/Softs/nloptr/revdep/checks.noindex/spaMM/new/spaMM.Rcheck/spaMM’ ``` -------------------------------- ### newuoa function signature Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/newuoa.md Defines the newuoa wrapper function. Parameters: x0 (starting point), fn (objective function), nl.info (logical to print nloptr result), control (list of options; algorithm overwritten with "NLOPT_LN_NEWUOA"), and ... (forwarded to fn). ```r newuoa <- function(x0, fn, nl.info = FALSE, control = list(), ...) { ``` -------------------------------- ### Powell's Singular Function (PSF) example Source: https://github.com/astamm/nloptr/blob/master/man/sbplx.Rd Example minimizing Powell's Singular Function with sbplx, using control options maxeval = Inf and ftol_rel = 1e-6. The expected optimum is approximately (0, 0, 0, 0), though the comment marks it with a question mark. ```r # Powell's Singular Function (PSF) psf <- function(x) (x[1] + 10*x[2])^2 + 5*(x[3] - x[4])^2 + (x[2] - 2*x[3])^4 + 10*(x[1] - x[4])^4 x0 <- c(3, -1, 0, 1) sbplx(x0, psf, control = list(maxeval = Inf, ftol_rel = 1e-6)) # 0 0 0 0 (?) ``` -------------------------------- ### NLopt tutorial example: objective, constraint, gradient, and Jacobian functions Source: https://github.com/astamm/nloptr/blob/master/man/nloptr.Rd Defines the objective function eval_f0, constraint function eval_g0, gradient eval_grad_f0, and Jacobian eval_jac_g0 for the NLopt tutorial problem. The problem is reformulated to constraints of form g(x) <= 0. Parameters a and b are defined for use with these functions. ```R # Example showing how to solve the problem from the NLopt tutorial. # # min sqrt(x2) # s.t. x2 >= 0 # x2 >= (a1*x1 + b1)^3 # x2 >= (a2*x1 + b2)^3 # where # a1 = 2, b1 = 0, a2 = -1, b2 = 1 # # re-formulate constraints to be of form g(x) <= 0 # (a1*x1 + b1)^3 - x2 <= 0 # (a2*x1 + b2)^3 - x2 <= 0 library('nloptr') # objective function eval_f0 <- function(x, a, b) { return(sqrt(x[2])) } # constraint function eval_g0 <- function(x, a, b) { return((a*x[1] + b)^3 - x[2]) } # gradient of objective function eval_grad_f0 <- function(x, a, b) { return(c(0, .5/sqrt(x[2]))) } # Jacobian of constraint eval_jac_g0 <- function(x, a, b) { return(rbind(c(3*a[1]*(a[1]*x[1] + b[1])^2, -1.0), c(3*a[2]*(a[2]*x[1] + b[2])^2, -1.0))) } # functions with gradients in objective and constraint function # this can be useful if the same calculations are needed for # the function value and the gradient eval_f1 <- function(x, a, b) { return(list("objective"=sqrt(x[2]), "gradient"=c(0,.5/sqrt(x[2])))) } eval_g1 <- function(x, a, b) { return(list("constraints"=(a*x[1] + b)^3 - x[2], "jacobian"=rbind(c(3*a[1]*(a[1]*x[1] + b[1])^2, -1.0), c(3*a[2]*(a[2]*x[1] + b[2])^2, -1.0)))) } # define parameters a <- c(2,-1) b <- c(0, 1) ``` -------------------------------- ### Basic scalar function example Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/check.derivatives.md Checks the gradient of a scalar function f(x) = sum((x-a)^2) against finite differences, with print mode 'none' and a random parameter a. ```r library(nloptr) f <- function(x, a) sum((x - a)^2) f_grad <- function(x, a) 2 * (x - a) res <- check.derivatives(.x = 1:10, func = f, func_grad = f_grad, check_derivatives_print = "none", a = runif(10)) identical(res$flag_derivative_warning, rep(FALSE, 10)) # correct gradient ``` -------------------------------- ### auglag example from alabama help page with lbfgs Source: https://github.com/astamm/nloptr/blob/master/man/auglag.Rd Defines objective, equality, and inequality functions from the alabama::auglag help page, then runs auglag with localsolver = "lbfgs". Expected parameters are roughly (0, 0, 1) with objective value 1. ```R fn <- function(x) (x[1] + 3 * x[2] + x[3]) ^ 2 + 4 * (x[1] - x[2]) ^ 2 heq <- function(x) x[1] + x[2] + x[3] - 1 # hin restated from alabama example to be <= 0. hin <- function(x) c(-6 * x[2] - 4 * x[3] + x[1] ^ 3 + 3, -x[1], -x[2], -x[3]) ``` ```R set.seed(12) auglag(runif(3), fn, hin = hin, heq = heq, localsolver= "lbfgs", deprecatedBehavior = FALSE) ``` ```output # $par: 4.861756e-08 4.732373e-08 9.999999e-01 # $value: 1 # $iter: 145 ``` -------------------------------- ### Basic use of bobyqa Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/bobyqa.md Minimizes the Rosenbrock function starting from (0,0). The optimal solution is at (1,1) with value 0. Access results via S$par and S$value. ```r library(nloptr) rbf <- function(x) (1 - x[1])^2 + 100 * (x[2] - x[1]^2)^2 # Rosenbrock S <- bobyqa(c(0, 0), rbf) # minimum 0 at (1, 1) S$par S$value ``` -------------------------------- ### Error handling with deprecation warning Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/slsqp.md Shows the deprecation warning emitted when using the old hin >= 0 convention (deprecatedBehavior = TRUE). The example calls slsqp() with an inequality constraint and triggers a warning about the deprecated behavior. ```r library(nloptr) # Deprecation warning for the old hin >= 0 convention: try(slsqp(c(1, 1), fn = function(x) sum(x^2), hin = function(x) c(1 - x[1]))) # -> Warning: The old behavior for hin >= 0 has been deprecated. ... ``` -------------------------------- ### stogo() error handling examples Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/stogo.md Shows that gr=NULL does not cause an error because the gradient is computed numerically via nl.grad, while an invalid algorithm name is rejected with 'Error: Incorrect algorithm supplied. Use one of the following: ...'. ```r library(nloptr) # Gradient-requiring algorithm without a gradient fails validation: try(stogo(x0 = c(0, 0), fn = function(x) sum(x^2), lower = c(-1, -1), upper = c(1, 1), gr = NULL)) # -> no error: gr is computed numerically via nl.grad # But an invalid algorithm name is rejected by is.nloptr: try(stogo(x0 = c(0, 0), fn = function(x) sum(x^2))) # -> Error: Incorrect algorithm supplied. Use one of the following: ... ``` -------------------------------- ### Minimize the Hartmann6 function with directL Source: https://github.com/astamm/nloptr/blob/master/man/direct.Rd Example that defines the Hartmann6 objective function and calls directL with xtol_rel = 1e-8 and maxeval = 1000. The displayed NLopt output shows the current objective value -3.32236800687327 and the corresponding control values after 1000 iterations. ```R ### Minimize the Hartmann6 function hartmann6 <- function(x) { a <- c(1.0, 1.2, 3.0, 3.2) A <- matrix(c(10.0, 0.05, 3.0, 17.0, 3.0, 10.0, 3.5, 8.0, 17.0, 17.0, 1.7, 0.05, 3.5, 0.1, 10.0, 10.0, 1.7, 8.0, 17.0, 0.1, 8.0, 14.0, 8.0, 14.0), nrow=4, ncol=6) B <- matrix(c(.1312,.2329,.2348,.4047, .1696,.4135,.1451,.8828, .5569,.8307,.3522,.8732, .0124,.3736,.2883,.5743, .8283,.1004,.3047,.1091, .5886,.9991,.6650,.0381), nrow=4, ncol=6) fun <- 0 for (i in 1:4) { fun <- fun - a[i] * exp(-sum(A[i,] * (x - B[i,]) ^ 2)) } fun } S <- directL(hartmann6, rep(0, 6), rep(1, 6), nl.info = TRUE, control = list(xtol_rel = 1e-8, maxeval = 1000)) ``` ```text ## Number of Iterations....: 1000 ## Termination conditions: stopval: -Inf ## xtol_rel: 1e-08, maxeval: 1000, ftol_rel: 0, ftol_abs: 0 ## Number of inequality constraints: 0 ## Number of equality constraints: 0 ## Current value of objective function: -3.32236800687327 ## Current value of controls: ## 0.2016884 0.1500025 0.4768667 0.2753391 0.311648 0.6572931 ``` -------------------------------- ### Load nloptr and read help Source: https://github.com/astamm/nloptr/blob/master/vignettes/nloptr.Rmd Loads the nloptr library and displays its help documentation. ```R library("nloptr") ?nloptr ``` -------------------------------- ### nloptr.print.options(opts.show, opts.user) Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/nloptr.print.options.md Prints a description of all or a subset of nloptr options. Optionally shows current values when user-supplied options are provided. ```APIDOC ## Function: nloptr.print.options(opts.show, opts.user) ### Description Prints a description of all (or a subset of) the options that can be set inside `opts` for `nloptr()`. Called internally by `nloptr()` when the option `print_options_doc = TRUE`. ### Signature ```r nloptr.print.options <- function(opts.show = NULL, opts.user = NULL) ``` ### Parameters - **opts.show** (list or vector of names) - Optional - Names of options to describe (subset by `name %in% opts.show`). Default shows all options. - **opts.user** (list) - Optional - User-supplied options. When given, the "current value" line is printed for each option (falling back to `"(default)"` when an option is not present in `opts.user`). ### Return Value `NULL` (invisible side effect: the documentation is printed to the console via `cat()`). ### Examples #### Basic use ```r library(nloptr) nloptr.print.options() nloptr.print.options(opts.show = c("algorithm", "check_derivatives")) ``` #### Show current values against defaults ```r library(nloptr) opts <- list(algorithm = "NLOPT_LD_LBFGS", xtol_rel = 1.0e-8) nloptr.print.options(opts.user = opts) ``` #### Integration with `nloptr()` ```r library(nloptr) # print_options_doc = TRUE triggers the same output during a solve res <- nloptr(x0 = c(1, 2), eval_f = function(x) sum((x - 1)^2), opts = list(algorithm = "NLOPT_LN_BOBYQA", print_options_doc = TRUE)) ``` #### Error handling ```r library(nloptr) # Unknown option names simply yield no matching rows (no error): nloptr.print.options(opts.show = c("does_not_exist")) # (no output) ``` ``` -------------------------------- ### Basic use of nloptr.print.options Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/nloptr.print.options.md Loads the nloptr library and prints descriptions of all options, or a subset specified by opts.show. ```r library(nloptr) nloptr.print.options() nloptr.print.options(opts.show = c("algorithm", "check_derivatives")) ``` -------------------------------- ### CRAN Installation Log Source: https://github.com/astamm/nloptr/blob/master/revdep/failures.md Log output from the CRAN version installation showing the same compilation failure due to missing gsl/gsl_sf_bessel.h header. ```text * installing *source* package ‘spaMM’ ... ** package ‘spaMM’ successfully unpacked and MD5 sums checked ** using staged installation ** libs using C++ compiler: ‘Apple clang version 16.0.0 (clang-1600.0.26.6)’ using SDK: ‘MacOSX15.2.sdk’ clang++ -arch arm64 -std=gnu++17 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/Rcpp/include' -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/RcppEigen/include' -I/opt/R/arm64/include -fPIC -falign-functions=64 -Wall -g -O2 -c COMPoisson.cpp -o COMPoisson.o clang++ -arch arm64 -std=gnu++17 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/Rcpp/include' -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/RcppEigen/include' -I/opt/R/arm64/include -fPIC -falign-functions=64 -Wall -g -O2 -c PLS.cpp -o PLS.o In file included from PLS.cpp:1: In file included from ./spaMM_linear.h:4: ... | ^ 5 warnings generated. clang++ -arch arm64 -std=gnu++17 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/Rcpp/include' -I'/Users/stamm-a/Softs/nloptr/revdep/library.noindex/spaMM/RcppEigen/include' -I/opt/R/arm64/include -fPIC -falign-functions=64 -Wall -g -O2 -c newBessel.cpp -o newBessel.o newBessel.cpp:2:10: fatal error: 'gsl/gsl_sf_bessel.h' file not found 2 | #include | ^~~~~~~~~~~~~~~~~~~~~ 1 error generated. make: *** [newBessel.o] Error 1 ERROR: compilation failed for package ‘spaMM’ * removing ‘/Users/stamm-a/Softs/nloptr/revdep/checks.noindex/spaMM/old/spaMM.Rcheck/spaMM’ ``` -------------------------------- ### Advanced configuration of newuoa with nl.info and control Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/newuoa.md Runs newuoa with nl.info = TRUE and control options xtol_rel = 1e-10, ftol_rel = 1e-12, maxeval = 5000. The stopifnot verifies successful termination (convergence > 0). ```r library(nloptr) S <- newuoa(c(1, 2), rbf, nl.info = TRUE, control = list(xtol_rel = 1e-10, ftol_rel = 1e-12, maxeval = 5000)) stopifnot(S$convergence > 0) # verify successful termination ``` -------------------------------- ### Show current values against defaults Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/nloptr.print.options.md Creates a list of user options and passes it to nloptr.print.options to display current values, falling back to '(default)' for options not in the list. ```r library(nloptr) opts <- list(algorithm = "NLOPT_LD_LBFGS", xtol_rel = 1.0e-8) nloptr.print.options(opts.user = opts) ``` -------------------------------- ### Print all nloptr options Source: https://github.com/astamm/nloptr/blob/master/man/nloptr.print.options.Rd Prints a description of all available nloptr options. Requires the nloptr package to be loaded. ```r library('nloptr') nloptr.print.options() ``` -------------------------------- ### Fletcher and Powell's helic valley example Source: https://github.com/astamm/nloptr/blob/master/man/sbplx.Rd Example minimizing the Fletcher and Powell helic valley function with sbplx. The expected optimum is approximately (1, 0, 0). ```r # Fletcher and Powell's helic valley fphv <- function(x) 100*(x[3] - 10*atan2(x[2], x[1])/(2*pi))^2 + (sqrt(x[1]^2 + x[2]^2) - 1)^2 +x[3]^2 x0 <- c(-1, 0, 0) sbplx(x0, fphv) # 1 0 0 ``` -------------------------------- ### Define objective function flb for lbfgs example Source: https://github.com/astamm/nloptr/blob/master/man/lbfgs.Rd Defines the objective function used in the lbfgs example. It computes a sum based on the vector x and is used with a 25-dimensional box-constrained optimization. ```r flb <- function(x) { p <- length(x) sum(c(1, rep(4, p-1)) * (x - c(1, x[-p])^2)^2) } ``` -------------------------------- ### nloptr() options list Source: https://github.com/astamm/nloptr/blob/master/_autodocs/configuration.md Configuration options for the nloptr() function and its wrappers. The options list is passed as 'opts' to nloptr() or 'control' to wrapper functions. Each option controls algorithm selection, termination conditions, or output behavior. ```APIDOC ## nloptr() options list ### Description Configuration options for the nloptr() function and its wrappers. The options list is passed as 'opts' to nloptr() or 'control' to wrapper functions. Each option controls algorithm selection, termination conditions, or output behavior. ### Parameters #### Options - **algorithm** (character) - Required - One of the 37 algorithm strings (see types.md). The wrapper functions set this themselves. - **stopval** (numeric) - Optional - Stop when an objective value <= stopval is found. -Inf disables (default). - **ftol_rel** (numeric) - Optional - Stop when an optimization step changes the objective value by less than ftol_rel * |f|. Disabled if non-positive (default). - **ftol_abs** (numeric) - Optional - Stop when an optimization step changes the function value by less than ftol_abs. Disabled if non-positive (default). - **xtol_rel** (numeric) - Optional - Stop when an optimization step changes every parameter by less than xtol_rel * |x_i|. Disabled if non-positive. Default is 1e-4 for nloptr(), 1e-6 for wrappers. - **x_weights** (numeric) - Optional - Vector of length n giving relative importance of each x[i] in the relative-tolerance check. Default: rep(1.0, length(x0)). - **xtol_abs** (numeric) - Optional - Vector of tolerances: stop when every parameter changes by less than xtol_abs[i]. Disabled if all non-positive (default). Default: rep(0.0, length(x0)). - **maxeval** (integer) - Optional - Stop when function evaluations exceed maxeval (approximate bound). Disabled if non-positive. Default: 100 for nloptr(), 1000 for wrappers. - **maxtime** (numeric) - Optional - Stop when optimization time (seconds) exceeds maxtime (approximate). Disabled if non-positive (default). Also drives the retry loop in nloptr() for spurious status 6. - **tol_constraints_ineq** (numeric) - Optional - Per-constraint tolerance for inequality stopping: x counted feasible when eval_g_ineq(x) <= tol. Default: rep(1e-8, num_constraints_ineq). - **tol_constraints_eq** (numeric) - Optional - Per-constraint tolerance for equality stopping: feasible when abs(eval_g_eq(x)) <= tol. Default: rep(1e-8, num_constraints_eq). - **print_level** (integer) - Optional - Output verbosity: 0 none; 1 iteration number + objective value; 2 = 1 + (in)equality values; 3 = 2 + controls. Default: 0. - **check_derivatives** (logical) - Optional - Compare user-supplied analytic gradients with finite-difference approximations before solving (check.derivatives()). Default: FALSE. - **check_derivatives_tol** (numeric) - Optional - Tolerance above which a gradient difference is flagged as an error. Default: 1e-04. - **check_derivatives_print** (character) - Optional - "all", "errors", or "none" — amount of derivative-checker output. Default: "all". - **print_options_doc** (logical) - Optional - If TRUE, print the description of all options (via nloptr.print.options) when solving. Default: FALSE. - **population** (integer) - Optional - Initial population size for stochastic global algorithms (CRS, MLSL, ISRES); 0 = heuristic default. Default: 0. - **vector_storage** (integer) - Optional - Number of gradients remembered from previous steps (LBFGS m, etc.). Default: 20. - **ranseed** (integer) - Optional - Random seed for stochastic algorithms; 0 = seed from system time (non-deterministic). Default: 0. #### Special Option: local_opts - **local_opts** (list) - Optional - Special option consumed by nloptr(): when "local_opts" %in% names(opts), its contents are processed recursively by nloptr.add.default.options (given the same x0 and constraint counts), stored in the result as local_options, and removed from options. Required by NLOPT_*_AUGLAG and NLOPT_*_MLSL algorithms (is.nloptr enforces this). Shape: list("algorithm" = , ), e.g. list(algorithm = "NLOPT_LD_MMA", xtol_rel = 1e-7). ### Notes - Unknown option names in opts.user are silently ignored by nloptr.add.default.options (only known names are iterated); values for known names pass through as-is (character options are taken directly, numeric/other defaults are parsed only when the option is absent). - If none of the termination-condition keys (stopval, ftol_rel, ftol_abs, xtol_rel, x_weights, xtol_abs, maxeval, maxtime) is present in opts.user, a warning is emitted and xtol_rel = 1e-4 is applied as default. ``` -------------------------------- ### Define Rosenbrock Banana function Source: https://github.com/astamm/nloptr/blob/master/man/bobyqa.Rd Defines the Rosenbrock Banana objective function used in the bobyqa examples. It has a minimum of 0 at (1, 1). ```r rbf <- function(x) {(1 - x[1]) ^ 2 + 100 * (x[2] - x[1] ^ 2) ^ 2} ``` -------------------------------- ### Load nloptr library Source: https://github.com/astamm/nloptr/blob/master/man/check.derivatives.Rd Loads the nloptr package before using check.derivatives. ```R library('nloptr') ``` -------------------------------- ### Call check.derivatives with print all Source: https://github.com/astamm/nloptr/blob/master/vignettes/nloptr.Rmd Calls check.derivatives at point c(1,2) with the user-supplied g and g_grad, using check_derivatives_print = "all" and a = c(0.3, 0.8). The output shows errors on screen and returns analytic and finite-difference values in a list. ```R res <- check.derivatives( .x = c(1, 2), func = g, func_grad = g_grad, check_derivatives_print = "all", a = c(0.3, 0.8) ) ``` -------------------------------- ### Fletcher and Powell's helic valley example Source: https://github.com/astamm/nloptr/blob/master/man/neldermead.Rd Minimizes the Fletcher and Powell helic valley function using neldermead. The expected result is approximately (1, 0, 0). ```R fphv <- function(x) 100*(x[3] - 10*atan2(x[2], x[1])/(2*pi))^2 + (sqrt(x[1]^2 + x[2]^2) - 1)^2 +x[3]^2 x0 <- c(-1, 0, 0) neldermead(x0, fphv) # 1 0 0 ``` -------------------------------- ### Basic use of sbplx() Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/sbplx.md Minimizes the fphv function starting from c(-1, 0, 0). The result S$par approximates c(1, 0, 0). ```r library(nloptr) fphv <- function(x) 100 * (x[3] - 10 * atan2(x[2], x[1]) / (2 * pi))^2 + (sqrt(x[1]^2 + x[2]^2) - 1)^2 + x[3]^2 S <- sbplx(c(-1, 0, 0), fphv) S$par # ~ c(1, 0, 0) ``` -------------------------------- ### slsqp(x0, fn, gr, lower, upper, hin, hinjac, heq, heqjac, nl.info, control, deprecatedBehavior, ...) Source: https://github.com/astamm/nloptr/blob/master/man/slsqp.Rd Runs the Sequential Quadratic Programming (SQP) algorithm for nonlinearly constrained, gradient-based optimization. It supports both equality and inequality constraints and returns a list with the optimal solution, function value, iteration count, convergence code, and message. ```APIDOC ## slsqp(x0, fn, gr, lower, upper, hin, hinjac, heq, heqjac, nl.info, control, deprecatedBehavior, ...) ### Description Runs the Sequential Quadratic Programming (SQP) algorithm for nonlinearly constrained, gradient-based optimization. It supports both equality and inequality constraints and returns a list with the optimal solution, function value, iteration count, convergence code, and message. ### Usage ```r slsqp( x0, fn, gr = NULL, lower = NULL, upper = NULL, hin = NULL, hinjac = NULL, heq = NULL, heqjac = NULL, nl.info = FALSE, control = list(), deprecatedBehavior = TRUE, ... ) ``` ### Arguments - **x0** (numeric vector) - Required - Starting point for searching the optimum. - **fn** (function) - Required - Objective function that is to be minimized. - **gr** (function) - Optional - Gradient of function `fn`; will be calculated numerically if not specified. - **lower** (numeric vector) - Optional - Lower bound constraints. - **upper** (numeric vector) - Optional - Upper bound constraints. - **hin** (function) - Optional - Function defining the inequality constraints, that is `hin <= 0` for all components. This is new behavior in line with the rest of the `nloptr` arguments. To use the old behavior, please set `deprecatedBehavior` to `TRUE`. - **hinjac** (function) - Optional - Jacobian of function `hin`; will be calculated numerically if not specified. - **heq** (function) - Optional - Function defining the equality constraints, that is `heq = 0` for all components. - **heqjac** (function) - Optional - Jacobian of function `heq`; will be calculated numerically if not specified. - **nl.info** (logical) - Optional - Shall the original NLopt info be shown. - **control** (list) - Optional - List of options, see `nl.opts` for help. - **deprecatedBehavior** (logical) - Optional - If `TRUE` (default for now), the old behavior of the Jacobian function is used, where the equality is `>= 0` instead of `<= 0`. This will be reversed in a future release and eventually removed. - **...** - Optional - Additional arguments passed to the function. ### Value Returns a list with components: - **par** - The optimal solution found so far. - **value** - The function value corresponding to `par`. - **iter** - Number of (outer) iterations, see `maxeval`. - **convergence** - Integer code indicating successful completion (> 1) or a possible error number (< 0). - **message** - Character string produced by NLopt and giving additional information. ### Example ```r ## Solve the Hock-Schittkowski problem no. 100 with analytic gradients ## See https://apmonitor.com/wiki/uploads/Apps/hs100.apm x0.hs100 <- c(1, 2, 0, 4, 0, 1, 1) fn.hs100 <- function(x) {(x[1] - 10) ^ 2 + 5 * (x[2] - 12) ^ 2 + x[3] ^ 4 + 3 * (x[4] - 11) ^ 2 + 10 * x[5] ^ 6 + 7 * x[6] ^ 2 + x[7] ^ 4 - 4 * x[6] * x[7] - 10 * x[6] - 8 * x[7]} hin.hs100 <- function(x) {c( 2 * x[1] ^ 2 + 3 * x[2] ^ 4 + x[3] + 4 * x[4] ^ 2 + 5 * x[5] - 127, 7 * x[1] + 3 * x[2] + 10 * x[3] ^ 2 + x[4] - x[5] - 282, 23 * x[1] + x[2] ^ 2 + 6 * x[6] ^ 2 - 8 * x[7] - 196, 4 * x[1] ^ 2 + x[2] ^ 2 - 3 * x[1] * x[2] + 2 * x[3] ^ 2 + 5 * x[6] - 11 * x[7]) } S <- slsqp(x0.hs100, fn = fn.hs100, # no gradients and jacobians provided hin = hin.hs100, nl.info = TRUE, control = list(xtol_rel = 1e-8, check_derivatives = TRUE), deprecatedBehavior = FALSE) ## The optimum value of the objective function should be 680.6300573 ## A suitable parameter vector is roughly ## (2.330, 1.9514, -0.4775, 4.3657, -0.6245, 1.0381, 1.5942) S ``` ``` -------------------------------- ### Load nloptr library Source: https://github.com/astamm/nloptr/blob/master/vignettes/nloptr.Rmd Loads the nloptr package into the R session. ```R library(nloptr) ``` -------------------------------- ### Advanced configuration of sbplx() Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/sbplx.md Uses control options maxeval = 100000 and ftol_rel = 1e-6 with the psf objective function starting from c(3, -1, 0, 1). ```r library(nloptr) psf <- function(x) (x[1] + 10 * x[2])^2 + 5 * (x[3] - x[4])^2 + (x[2] - 2 * x[3])^4 + 10 * (x[1] - x[4])^4 S <- sbplx(c(3, -1, 0, 1), psf, control = list(maxeval = 100000, ftol_rel = 1e-6)) ``` -------------------------------- ### Print specific nloptr options with opts.show Source: https://github.com/astamm/nloptr/blob/master/man/nloptr.print.options.Rd Prints descriptions for only the options named in the opts.show argument, here 'algorithm' and 'check_derivatives'. ```r nloptr.print.options(opts.show = c("algorithm", "check_derivatives")) ``` -------------------------------- ### lbfgs() function signature Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/lbfgs.md Signature of the lbfgs() function in R. It initializes the low-storage BFGS optimizer with parameters for starting point, objective function, gradient, bounds, and control options. ```r lbfgs <- function( x0, fn, gr = NULL, lower = NULL, upper = NULL, nl.info = FALSE, control = list(), ... ) ``` -------------------------------- ### varmetric example with box constraints Source: https://github.com/astamm/nloptr/blob/master/man/varmetric.Rd Minimizes the Rosenbrock-like function flb in 25 dimensions with box constraints [2,4]. The optimal value is 368.105912874334, with controls at 2 ... 2 2.109093 4. ```r flb <- function(x) { p <- length(x) sum(c(1, rep(4, p-1)) * (x - c(1, x[-p])^2)^2) } # 25-dimensional box constrained: par[24] is *not* at the boundary S <- varmetric(rep(3, 25), flb, lower=rep(2, 25), upper=rep(4, 25), nl.info = TRUE, control = list(xtol_rel=1e-8)) ## Optimal value of objective function: 368.105912874334 ## Optimal value of controls: 2 ... 2 2.109093 4 ``` -------------------------------- ### Run bobyqa with bounds [0, 0.5] Source: https://github.com/astamm/nloptr/blob/master/man/bobyqa.Rd Calls bobyqa with both parameters constrained to [0, 0.5] using lower and upper arguments. The result is stored in S and then printed. ```r S <- bobyqa(c(0, 0), rbf, lower = c(0, 0), upper = c(0.5, 0.5)) ``` ```r S ``` -------------------------------- ### Basic use of nl.opts() Source: https://github.com/astamm/nloptr/blob/master/_autodocs/api-reference/nl.opts.md Creates an options list overriding xtol_rel and maxeval, then inspects the resulting values. The algorithm entry remains NULL until a wrapper sets it. ```r library(nloptr) opts <- nl.opts(list(xtol_rel = 1e-8, maxeval = 2000)) opts$xtol_rel # 1e-8 opts$maxeval # 2000 opts$algorithm # NULL ``` -------------------------------- ### Powell's Singular Function (PSF) example Source: https://github.com/astamm/nloptr/blob/master/man/neldermead.Rd Minimizes Powell's Singular Function using neldermead. The expected result is (0, 0, 0, 0), but requires the maximum number of function calls. ```R psf <- function(x) (x[1] + 10*x[2])^2 + 5*(x[3] - x[4])^2 + (x[2] - 2*x[3])^4 + 10*(x[1] - x[4])^4 x0 <- c(3, -1, 0, 1) neldermead(x0, psf) # 0 0 0 0, needs maximum number of function calls ``` -------------------------------- ### Solve with NLOPT_LD_MMA using gradient and Jacobian Source: https://github.com/astamm/nloptr/blob/master/vignettes/nloptr.Rmd Calls nloptr with NLOPT_LD_MMA, supplying lower bounds lb = c(-Inf, 0), upper bounds ub = c(Inf, Inf), inequality constraints via eval_g_ineq, and Jacobian via eval_jac_g_ineq. Enables derivative checking with check_derivatives = TRUE and print_level = 2. The result is printed. ```R # Solve using NLOPT_LD_MMA with gradient information supplied in separate # function res0 <- nloptr(x0 = c(1.234, 5.678), eval_f = eval_f0, eval_grad_f = eval_grad_f0, lb = c(-Inf, 0), ub = c(Inf, Inf), eval_g_ineq = eval_g0, eval_jac_g_ineq = eval_jac_g0, opts = list("algorithm" = "NLOPT_LD_MMA", "xtol_rel" = 1.0e-8, "print_level" = 2, "check_derivatives" = TRUE, "check_derivatives_print" = "all"), a = a, b = b) print(res0) ``` -------------------------------- ### Print nloptr options with user-supplied options Source: https://github.com/astamm/nloptr/blob/master/man/nloptr.print.options.Rd Prints options based on a user-supplied list of options. The opts.user argument is used when called from nloptr, and options are listed if print_options_doc is TRUE. ```r opts <- list("algorithm"="NLOPT_LD_LBFGS", "xtol_rel"=1.0e-8) nloptr.print.options(opts.user = opts) ```