### Run Knitro Python Examples Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startPython Command to execute Knitro Python example scripts from the `Python/examples` folder, using the Python interpreter. ```bash python example*.py ``` -------------------------------- ### Install Knitro Python Package Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startPython Command to install the Knitro Python package using the `setup.py` script, typically run from the Python directory of the Knitro distribution. ```bash python setup.py install ``` -------------------------------- ### Test Knitro MATLAB Installation Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startMatlab This MATLAB command tests if the Knitro interface is correctly installed and accessible by calling a simple optimization problem to minimize `cos(x)` starting from `x=1`. ```MATLAB [x fval] = knitro_nlp(@(x)cos(x),1) ``` -------------------------------- ### Install KnitroR Package from Local Directory Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startR This command installs the KnitroR package from a local source. Users should navigate to the directory containing the `KnitroR` folder (e.g., `$KNITRODIR/examples/R`) before executing this command. ```R R CMD INSTALL KnitroR ``` -------------------------------- ### Verify KnitroR Installation and Run Basic Optimization Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startR This R code snippet loads the `KnitroR` library and executes a simple unconstrained optimization problem. It serves as a crucial step to confirm the successful installation of the package and demonstrates the fundamental usage of the `knitro` function with a custom objective. ```R library('KnitroR') knitro(objective = function(x) x[1] * x[2], x0 = c(1, 1)) ``` -------------------------------- ### Example Knitro Options File Format Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/knitroOptions Shows the structure of a Knitro options file, which allows setting parameters externally. Each line specifies a keyword and its value. Lines starting with '#' are comments. An example sets the maximum iterations. ```Configuration File # Knitro Options file maxit 500 ``` -------------------------------- ### KnitroR Optimization Solver Output Example Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startR This extensive output block illustrates the detailed results and statistics returned by the Knitro solver after running an optimization problem. It includes license information, problem characteristics, iteration progress, final solution statistics, and the returned R object containing solution values. ```R ======================================= Commercial License Artelys Knitro 14.2.0 ======================================= Knitro performing finite-difference gradient computation with 1 thread. Knitro presolve eliminated 0 variables and 0 constraints. concurrent_evals: 0 The problem is identified as unconstrained. Problem Characteristics ( Presolved) ----------------------- Objective goal: Minimize Objective type: general Number of variables: 2 ( 2) bounded below only: 0 ( 0) bounded above only: 0 ( 0) bounded below and above: 0 ( 0) fixed: 0 ( 0) free: 2 ( 2) Number of constraints: 0 ( 0) linear equalities: 0 ( 0) quadratic equalities: 0 ( 0) gen. nonlinear equalities: 0 ( 0) linear one-sided inequalities: 0 ( 0) quadratic one-sided inequalities: 0 ( 0) gen. nonlinear one-sided inequalities: 0 ( 0) linear two-sided inequalities: 0 ( 0) quadratic two-sided inequalities: 0 ( 0) gen. nonlinear two-sided inequalities: 0 ( 0) Number of nonzeros in Jacobian: 0 ( 0) Number of nonzeros in Hessian: 0 ( 3) Knitro using the Interior-Point/Barrier Direct algorithm. Iter Objective FeasError OptError ||Step|| CGits -------- -------------- ---------- ---------- ---------- ------- 0 1.000000e+00 0.000e+00 1 0.000000e+00 0.000e+00 0.000e+00 1.414e+00 0 EXIT: Locally optimal solution found. Final Statistics ---------------- Final objective value = 0.00000000000000e+00 Final feasibility error (abs / rel) = 0.00e+00 / 0.00e+00 Final optimality error (abs / rel) = 0.00e+00 / 0.00e+00 # of iterations = 1 # of CG iterations = 0 # of function evaluations = 8 # of gradient evaluations = 0 Total program time (secs) = 0.04607 ( 0.047 CPU time) Time spent in evaluations (secs) = 0.00001 =============================================================================== $status [1] 0 $obj [1] 0 $x [1] 0 0 $lambda [1] 0 0 $objGrad [1] 0 0 $objGradIndexVars [1] 0 1 $c NULL $r NULL $jac NULL $jacIndexCons NULL $jacIndexVars NULL $rsdJac NULL $rsdJacIndexRsds NULL $rsdJacIndexVars NULL $numFCevals [1] 8 $numGAevals [1] 0 $numHevals [1] 0 $numHVevals [1] 0 $numIters [1] 1 $numCGiters [1] 8 ``` -------------------------------- ### Solve QCQP with Knitro C Callable Library Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startCallableLibrary This C code snippet demonstrates how to define and solve a Quadratic Constrained Quadratic Program (QCQP) problem using the Knitro C callable library. It initializes a Knitro context, sets variable bounds and initial values, adds linear and quadratic constraints, defines a quadratic objective function, solves the problem, and prints the solution details including objective value, primal values, and error metrics. This example is equivalent to `exampleQCQP.c` provided with the Knitro distribution. ```C #include #include #include "knitro.h" /* main */ int main (int argc, char *argv[]) { int i, nStatus, error; /** Declare variables. */ KN_context *kc; int n, m; double x[3]; double xLoBnds[3] = {0, 0, 0}; double xInitVals[3] = {2.0, 2.0, 2.0}; /** Used to define linear constraint. */ int lconIndexVars[3] = { 0, 1, 2}; double lconCoefs[3] = {8.0, 14.0, 7.0}; /** Used to specify quadratic constraint. */ int qconIndexVars1[3] = { 0, 1, 2}; int qconIndexVars2[3] = { 0, 1, 2}; double qconCoefs[3] = {1.0, 1.0, 1.0}; /** Used to specify quadratic objective terms. */ int qobjIndexVars1[5] = { 0, 1, 2, 0, 0}; int qobjIndexVars2[5] = { 0, 1, 2, 1, 2}; double qobjCoefs[5] = {-1.0, -2.0, -1.0, -1.0, -1.0}; /** Solution information */ double objSol; double feasError, optError; /** Create a new Knitro solver instance. */ error = KN_new(&kc); if (error) exit(-1); if (kc == NULL) { printf ("Failed to find a valid license.\n"); return( -1 ); } /** Illustrate how to override default options by reading from * the knitro.opt file. */ error = KN_load_param_file (kc, "knitro.opt"); if (error) exit(-1); /** Initialize Knitro with the problem definition. */ /** Add the variables and set their bounds and initial values. * Note: unset bounds assumed to be infinite. */ n = 3; error = KN_add_vars(kc, n, NULL); if (error) exit(-1); error = KN_set_var_lobnds_all(kc, xLoBnds); if (error) exit(-1); error = KN_set_var_primal_init_values_all(kc, xInitVals); if (error) exit(-1); /** Add the constraints and set their bounds. */ m = 2; error = KN_add_cons(kc, m, NULL); if (error) exit(-1); error = KN_set_con_eqbnd(kc, 0, 56.0); if (error) exit(-1); error = KN_set_con_lobnd(kc, 1, 25.0); if (error) exit(-1); /** Add coefficients for linear constraint. */ error = KN_add_con_linear_struct_one (kc, 3, 0, lconIndexVars, lconCoefs); if (error) exit(-1); /** Add coefficients for quadratic constraint */ error = KN_add_con_quadratic_struct_one (kc, 3, 1, qconIndexVars1, qconIndexVars2, qconCoefs); if (error) exit(-1); /** Set minimize or maximize (if not set, assumed minimize) */ error = KN_set_obj_goal(kc, KN_OBJGOAL_MINIMIZE); if (error) exit(-1); /** Add constant value to the objective. */ error= KN_add_obj_constant(kc, 1000.0); if (error) exit(-1); /** Set quadratic objective structure. */ error = KN_add_obj_quadratic_struct (kc, 5, qobjIndexVars1, qobjIndexVars2, qobjCoefs); if (error) exit(-1); /** Solve the problem. * * Return status codes are defined in "knitro.h" and described * in the Knitro manual. */ nStatus = KN_solve (kc); printf ("\n\n"); printf ("Knitro converged with final status = %d\n", nStatus); /** An example of obtaining solution information. */ error = KN_get_solution(kc, &nStatus, &objSol, x, NULL); if (!error) { printf (" optimal objective value = %e\n", objSol); printf (" optimal primal values x = (%e, %e, %e)\n", x[0], x[1], x[2]); } error = KN_get_abs_feas_error (kc, &feasError); if (!error) printf (" feasibility violation = %e\n", feasError); error = KN_get_abs_opt_error (kc, &optError); if (!error) printf (" KKT optimality violation = %e\n", optError); /** Delete the Knitro solver instance. */ KN_free (&kc); return( 0 ); } ``` -------------------------------- ### Running Knitro Solver with AMPL Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startAmpl This AMPL script demonstrates how to initialize the Knitro solver, set specific options like `algorithm` and `bar_maxcrossit` for solution refinement and output level, load a model, and execute the solve command. It highlights the ease of controlling Knitro's behavior via `knitro_options`. ```AMPL ampl: reset; ampl: option solver knitroampl; ampl: option knitro_options "algorithm=2 bar_maxcrossit=2 outlev=1"; ampl: model testproblem.mod; ampl: solve; ``` -------------------------------- ### Set LD_LIBRARY_PATH for Knitro on Linux Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startPython Bash command to export the `LD_LIBRARY_PATH` environment variable, ensuring the Knitro library directory is discoverable by the system on Linux. ```bash export LD_LIBRARY_PATH=/path/to/knitrodirectory/lib ``` -------------------------------- ### Apply Bashrc Changes on Linux Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startPython Command to immediately source and apply the changes made to the `.bashrc` file in the current shell session on Linux. ```bash source .bashrc ``` -------------------------------- ### Run KnitroR Script from R Command Prompt Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startR This R command shows how to execute an R script named 'example.R' from the R command prompt. This allows the optimization problem defined within the file to be run and processed by KnitroR. ```R source('example.R') ``` -------------------------------- ### Knitro R Function: Simple Call Examples Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/3_referenceManual/knitroRreference These examples demonstrate the simplest ways to call the `knitro` function in R, requiring only an objective function and initial guess or bounds. They illustrate minimal configurations for problem setup. ```R res <- knitro(objective=..., x0=...) res <- knitro(objective=..., xL=...) res <- knitro(objective=..., xU=...) res <- knitro(nvar=..., objective=...) ``` -------------------------------- ### Knitro Callable Library API Workflow for Problem Solving Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startCallableLibrary Describes the typical sequence of function calls to use the Knitro callable library for building and solving optimization problems. It outlines the steps from context creation to problem solving and resource deallocation, highlighting key API functions for defining variables, constraints, special structures, and callbacks. ```APIDOC KN_new(): Create a new Knitro solver context pointer, allocating resources. KN_add_vars()/KN_add_cons()/KN_set_*bnds(): Add basic problem information (variables, constraints, bounds). KN_add_*_linear_struct()/KN_add_*_quadratic_struct(): Add special problem structures (linear, quadratic). KN_add_eval_callback(): Add callback for nonlinear evaluations if needed. KN_set_cb_*(): Set properties for nonlinear evaluation callbacks. KN_set_*_param(): Set user options/parameters. KN_solve(): Solve the optimization problem. KN_free(): Delete the Knitro context pointer, releasing allocated resources. ``` -------------------------------- ### Knitro 14.2 Compiler and Environment Details Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/1_introduction/installation This snippet details the specific C/C++, Java, and R compilers and their versions used to build and test Knitro 14.2 across various supported platforms, including Windows, Linux, and Mac OS X (Intel and ARM64). ```Plaintext > Windows (64-bit x86_64) > > C/C++: > Intel C/C++ compiler 17.0.4 > > Java: > 1.6 > > R: > R 3.0 (R interface) > Linux (64-bit x86_64) > > C/C++: > Intel C/C++ compiler 18.0.3 > > Java: > 1.6 > > R: > R 3.0 (R interface) > Mac OS X (64-bit x86_64) > > C/C++: > Intel C/C++ compiler 19.1 > > Java: > 1.6 > > R: > R 3.0 (R interface) > Mac OS X (arm64) > > C/C++: > Apple clang C/C++ compiler 12.0.0 ``` -------------------------------- ### Import Knitro Library in Python Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startPython This Python snippet demonstrates the essential first step for using the Knitro solver: importing all necessary components from the `knitro` library. This import statement makes Knitro's functions and classes available for use in an optimization script. ```Python from knitro import * ``` -------------------------------- ### Initialize Knitro Solver with Callable Library in Python Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startPython This Python snippet demonstrates how to create a new Knitro solver instance using the callable library interface. It includes error handling for license validation and shows how to load default options from a `knitro.opt` file. ```python from knitro import * # Create a new Knitro solver instance. try: kc = KN_new () except: print ("Failed to find a valid license.") quit () # Illustrate how to override default options by reading from # the knitro.opt file. KN_load_param_file (kc, "knitro.opt") ``` -------------------------------- ### Build PDF Documentation for KnitroR Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startR This command generates the comprehensive PDF documentation for the KnitroR package. It utilizes the `Rd2pdf` utility to compile the R documentation files into a readable PDF format. ```R R CMD Rd2pdf KnitroR ``` -------------------------------- ### Example AMPL Model for Optimization Problem Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startAmpl This AMPL model defines a non-linear optimization problem with three non-negative variables, an objective function to minimize, and two constraints (one equality, one inequality). It also includes an initial point for the variables. This example demonstrates how to formulate an optimization problem in AMPL for use with Knitro. ```AMPL # Example problem formulated as an AMPL model used # to demonstate using Knitro with AMPL. # The problem has two local solutions: # the point (0,0,8) with objective 936.0, and # the point (7,0,0) with objective 951.0 # Define variables and enforce that they be non-negative. var x{j in 1..3} >= 0; # Objective function to be minimized. minimize obj: 1000 - x[1]^2 - 2*x[2]^2 - x[3]^2 - x[1]*x[2] - x[1]*x[3]; # Equality constraint. s.t. c1: 8*x[1] + 14*x[2] + 7*x[3] - 56 = 0; # Inequality constraint. s.t. c2: x[1]^2 + x[2]^2 + x[3]^2 -25 >= 0; data; # Define initial point. let x[1] := 2; let x[2] := 2; let x[3] := 2; ``` -------------------------------- ### Knitro Solver Output Log Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startCallableLibrary This log displays the detailed output from a Knitro solver run, showing problem characteristics, iteration progress, and final statistics including objective value, feasibility, optimality errors, and execution time. It illustrates the solver's behavior and convergence. ```Output ======================================= Commercial License Artelys Knitro 14.2.0 ======================================= Knitro presolve eliminated 0 variables and 0 constraints. The problem is identified as a QCQP. Problem Characteristics ( Presolved) ----------------------- Objective goal: Minimize Objective type: quadratic Number of variables: 3 ( 3) bounded below only: 3 ( 3) bounded above only: 0 ( 0) bounded below and above: 0 ( 0) fixed: 0 ( 0) free: 0 ( 0) Number of constraints: 2 ( 2) linear equalities: 1 ( 1) quadratic equalities: 0 ( 0) gen. nonlinear equalities: 0 ( 0) linear one-sided inequalities: 0 ( 0) quadratic one-sided inequalities: 1 ( 1) gen. nonlinear one-sided inequalities: 0 ( 0) linear two-sided inequalities: 0 ( 0) quadratic two-sided inequalities: 0 ( 0) gen. nonlinear two-sided inequalities: 0 ( 0) Number of nonzeros in Jacobian: 6 ( 6) Number of nonzeros in Hessian: 5 ( 5) Iter Objective FeasError OptError ||Step|| CGits -------- -------------- ---------- ---------- ---------- ------- 0 9.760000e+02 1.300e+01 9 9.360000e+02 0.000e+00 1.515e-09 5.910e-05 0 Knitro using the Interior-Point/Barrier Direct algorithm. EXIT: Locally optimal solution found. Final Statistics ---------------- Final objective value = 9.36000000015579e+02 Final feasibility error (abs / rel) = 0.00e+00 / 0.00e+00 Final optimality error (abs / rel) = 1.51e-09 / 9.47e-11 # of iterations = 9 # of CG iterations = 2 # of function evaluations = 0 # of gradient evaluations = 0 # of Hessian evaluations = 0 Total program time (secs) = 0.00207 ( 0.001 CPU time) Time spent in evaluations (secs) = 0.00000 =============================================================================== Knitro converged with final status = 0 optimal objective value = 9.360000e+02 optimal primal values x = (1.514577e-09, 1.484137e-14, 8.000000e+00) feasibility violation = 0.000000e+00 KKT optimality violation = 1.514577e-09 ``` -------------------------------- ### Install OpenMP Library on MacOS with Homebrew Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/1_introduction/troubleshooting Command to install the 'libomp' library using Homebrew on MacOS, which can resolve security warnings when using Knitro's OpenMP features. ```Bash brew install libomp ``` -------------------------------- ### Check R Version on Apple Silicon Mac Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startR This code snippet displays the R version and platform information for Macs equipped with Apple silicon processors. The 'Platform' keyword in the output will indicate 'aarch64-apple-darwin' for Apple silicon. ```R R version 4.1.1 (2021-08-10) -- "Kick Things" Copyright (C) 2021 The R Foundation for Statistical Computing Platform: aarch64-apple-darwin20 (64-bit) ``` -------------------------------- ### Displaying Solution Variables in AMPL Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startAmpl This AMPL command demonstrates how to use the `display` command to inspect the values of variables (e.g., `x`) after an optimization problem has been solved by Knitro. It shows the variable indices and their corresponding optimal values. ```AMPL ampl: display x; x [*] := 1 0 2 0 3 8 ; ``` -------------------------------- ### Check R Version on Intel Mac Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startR This code snippet displays the R version and platform information for Macs equipped with Intel processors. The 'Platform' keyword in the output will indicate 'x86_64-apple-darwin' for Intel processors. ```R R version 4.3.1 (2023-06-16) -- "Beagle Scouts" Copyright (C) 2023 The R Foundation for Statistical Computing Platform: x86_64-apple-darwin20.6.0 (64-bit) ``` -------------------------------- ### AMPL Session with Knitro Presolve Debug Output Example Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/obtainingInformation This example demonstrates an AMPL session configuring Knitro to output presolve debugging information. It shows the setup for loading a model, selecting Knitro, enabling auxiliary files, and setting Knitro options to display the problem structure as seen by Knitro, including the mapping between Knitro's internal names and the original AMPL model names. ```AMPL ampl: model testproblem.mod; ampl: option solver knitroampl; ampl: option knitroampl_auxfiles rc; ampl: option knitro_options "presolve_dbg=2 outlev=0"; Artelys Knitro 14.2.0: presolve_dbg=2 outlev=0 ----- Problem seen by Knitro ----- Objective name: obj 0.000000e+00 <= x[ 0] <= 1.797693e+308 x[1] 0.000000e+00 <= x[ 1] <= 1.797693e+308 x[2] 0.000000e+00 <= x[ 2] <= 1.797693e+308 x[3] 2.500000e+01 <= c[ 0] <= 1.797693e+308 c2 (quadratic) 5.600000e+01 <= c[ 1] <= 5.600000e+01 c1 (linear) ----------------------------------- Knitro 14.2.0: Locally optimal or satisfactory solution. objective 936; feasibility error 0 10 iterations; 0 function evaluations ``` -------------------------------- ### Apply Bash Profile Changes on macOS Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startPython Command to immediately source and apply the changes made to the `~/.bash_profile` file in the current shell session on Mac OS X. ```bash source ~/.bash_profile ``` -------------------------------- ### Complete Example of a Free MPS Format File Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/mpsFiles A comprehensive example demonstrating the structure and content of a problem defined in the free MPS format, including sections for NAME, ROWS, COLUMNS, RHS, and BOUNDS. This example illustrates how to define an optimization problem for Knitro. ```MPS NAME TESTPROB ROWS N COST L LIM1 G LIM2 E MYEQN COLUMNS XONE COST 1 LIM1 1 XONE LIM2 1 YTWO COST 4 LIM1 1 YTWO MYEQN -1 ZTHREE COST 9 LIM2 1 ZTHREE MYEQN 1 RHS RHS1 LIM1 5 LIM2 10 RHS1 MYEQN 7 BOUNDS UP BND1 XONE 4 LO BND1 YTWO -1 UP BND1 YTWO 1 ENDATA ``` -------------------------------- ### Knitro C++ Example: Defining Nonlinear Constraints and Main Program Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/3_referenceManual/ooInterfaceReference This comprehensive C++ example demonstrates how to define nonlinear constraint blocks using `KNNonLinearBloc` and `KNEvalCallback`, and integrate them into a Knitro problem. It includes the `main` function showing problem instantiation, solver setup, parameter setting (e.g., `hessopt`), execution, and retrieval of solution results like objective value, primal values, and error metrics. ```cpp KNNonLinearBloc c0bloc(cst_indexes, callback, jacNnzPattern, hessNnzPattern); this->getConstraintsNonLinearParts().push_back(c0bloc); } void setNonLinearC1() { KNEvalCallback callback(&ProblemNLP2::callbackEvalC1, NULL, NULL, NULL); KNSparseMatrixStructure jacNnzPattern = { {1,1}, {0,3} }; KNSparseMatrixStructure hessNnzPattern; std::vector cst_indexes = {1}; KNNonLinearBloc c1bloc(cst_indexes, callback, jacNnzPattern, hessNnzPattern); this->getConstraintsNonLinearParts().push_back(c1bloc); } }; int main() { // Create a problem instance. ProblemNLP2 instance = ProblemNLP2(); // Create a solver knitro::KNSolver solver(&instance); /** Set option to print output after every iteration. */ solver.setParam("hessopt", KN_HESSOPT_BFGS); solver.initProblem(); int solveStatus = solver.solve(); std::vector x; std::vector lambda; int nStatus = solver.getSolution(x, lambda); printf ("Knitro converged with final status = %d\n", nStatus); printf (" optimal objective value = %e\n", solver.getObjValue()); printf (" optimal primal values x = (%e, %e, %e, %e)\n", x[0], x[1], x[2], x[3]); printf (" feasibility violation = %e\n", solver.getAbsFeasError()); printf (" KKT optimality violation = %e\n", solver.getAbsOptError()); return 0; } ``` -------------------------------- ### Initialize KNSolver with Artelys License Manager (ALM) in C++ Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/3_referenceManual/ooInterfaceReference This C++ example demonstrates how to use the Artelys License Manager (ALM) with the Knitro object-oriented interface. It shows the instantiation of an 'ALM' object, which manages the network license, and how this object is then passed to the 'KNSolver' constructor to enable license-controlled problem solving. This setup ensures a network license is checked out for the solver's duration. ```C++ int main() { knitro::ALM alm; // Create a problem instance. ProblemQCQP instance = ProblemQCQP(); // Create a solver KNSolver solver(&alm, &instance); int solveStatus = solver.solve(); return 0; } ``` -------------------------------- ### Knitro Solver Output for MATLAB Example Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/complementarity This snippet shows the console output from Knitro after running the provided MATLAB example. It details the solver's configuration, problem characteristics (variables, constraints, complementarities), iteration progress, and final statistics, confirming that a locally optimal solution was found. ```Text ======================================= Commercial License Artelys Knitro 14.2.0 ======================================= Knitro presolve eliminated 0 variables and 0 constraints. algorithm: 1 concurrent_evals: 0 feastol: 1e-08 honorbnds: 1 maxit: 1000 opttol: 1e-08 outlev: 4 The problem is identified as an MPEC. Knitro changing bar_initpt from AUTO to 3. Knitro changing bar_murule from AUTO to 4. Knitro changing bar_penaltycons from AUTO to 1. Knitro changing bar_penaltyrule from AUTO to 2. Knitro changing bar_switchrule from AUTO to 1. Knitro changing linsolver from AUTO to 2. Knitro shifted start point to satisfy presolved bounds (8 variables). Problem Characteristics ( Presolved) ----------------------- Objective goal: Minimize Objective type: general Number of variables: 8 ( 8) bounded below only: 8 ( 8) bounded above only: 0 ( 0) bounded below and above: 0 ( 0) fixed: 0 ( 0) free: 0 ( 0) Number of constraints: 4 ( 4) linear equalities: 4 ( 4) quadratic equalities: 0 ( 0) gen. nonlinear equalities: 0 ( 0) linear one-sided inequalities: 0 ( 0) quadratic one-sided inequalities: 0 ( 0) gen. nonlinear one-sided inequalities: 0 ( 0) linear two-sided inequalities: 0 ( 0) quadratic two-sided inequalities: 0 ( 0) gen. nonlinear two-sided inequalities: 0 ( 0) Number of complementarities: 3 ( 3) Number of nonzeros in Jacobian: 14 ( 14) Number of nonzeros in Hessian: 2 ( 2) Knitro using the Interior-Point/Barrier Direct algorithm. Iter fCount Objective FeasError OptError ||Step|| CGits -------- -------- -------------- ---------- ---------- ---------- ------- 0 2 2.496050e+01 4.030e+00 1 3 2.847389e+01 1.748e+00 2.160e+00 1.990e+00 1 2 4 4.226663e+01 3.832e-01 4.643e+00 1.442e+00 0 3 5 4.667799e+01 1.126e-02 3.638e+00 5.993e-01 0 4 6 4.213217e+01 4.179e-03 1.258e+01 1.185e+00 0 5 7 4.074018e+01 3.072e-03 1.265e+01 1.580e-01 1 6 8 3.810894e+01 1.133e-04 1.259e+01 3.113e-01 0 7 9 1.701407e+01 1.682e-04 1.542e+00 4.771e+00 0 8 10 1.699966e+01 1.522e-04 6.416e-02 2.385e-02 0 9 11 1.700003e+01 1.799e-06 3.532e-05 2.154e-04 0 10 12 1.700000e+01 6.354e-11 1.530e-09 5.298e-05 0 EXIT: Locally optimal solution found. Final Statistics ---------------- ``` -------------------------------- ### Unpack Knitro Gzipped Tar Archive on Unix Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/1_introduction/installation/unix Commands to decompress and extract the Knitro software package from a gzipped tar file on Unix systems (Linux, Mac OS X). Replace `|release|` and `|platformname|` with the actual version and platform details. ```Shell gunzip knitro-|release|-platformname.tar.gz tar -xvf knitro-|release|-platformname.tar ``` -------------------------------- ### Load Knitro Tuner Options File in AMPL Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/tuner This example demonstrates how to configure Knitro within an AMPL environment to enable the Tuner and specify an external options file. The `tuner_optionsfile` option is used to point to a custom Tuner configuration, allowing for flexible setup of optimization runs. ```AMPL ampl: option knitro_options "tuner=1 tuner_optionsfile='tuner-explore.opt'"; ``` -------------------------------- ### AMPL Example for Nonlinear Least-Squares with Knitro API Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/3_referenceManual/knitroamplReference This comprehensive AMPL script demonstrates three methods for solving least-squares problems: a direct formulation, an optimized expanded formulation, and the recommended approach using Knitro's specialized least-squares API. It includes setup for random data, variable definitions, and objective functions for each method, highlighting the required AMPL and Knitro options for the API-based solution. ```AMPL # ########################################################### # #### LSQ in AMPL with Knitro #### # #### #### # #### This example illustrates how to optimize least #### # #### squares problems in AMPL by formulating it using #### # #### AMPL syntax and also using Knitro least squares #### # #### dedicated API. #### # ########################################################### # Reset AMPL reset; # Reset initial guesses between consecutive runs option reset_initial_guesses 1; # Reinitialize random seed for generating same values over runs option randseed 1; ### The first part of the example will demonstrate how to formulate a ### least squares problem in AMPL using usual AMPL syntax. ### Also, we will illustrate an AMPL trick to improve performances. # We use a large number to demonstrate the AMPL expansion trick param M := 1000000; # Create random values for the "estimates" param alpha{1..M}; let{i in 1..M} alpha[i] := Uniform01(); # Variable: minimize the sum of squares of the distance between var_alpha # and the "estimates" var var_alpha; ### 1. Straightforward least squares formulation with no expansion ## Straightforward least square problem. ## The objective is expressed directly, without expanding the square terms. minimize obj_no_expand: 0.5 * sum{i in 1..M} (alpha[i]-var_alpha)^2; # Optimize non-expanded problem solve obj_no_expand; ### 2. Least squares with square terms expansion ## Same problem but this time the objective is expanded. ## Notice that, using this trick, the runtime decreases significantly. minimize obj_expanded: 0.5 * ( M * var_alpha^2 - 2 * var_alpha * ( sum{i in 1..M} alpha[i] ) + sum{i in 1..M} alpha[i]^2 ); # Optimize expanded problem solve obj_expanded; # Check objective value display obj_expanded - obj_no_expand; ### 3. Least squares using Knitro LSQ API # Set Ampl and Knitro options option presolve 0; # disable AMPL presolve, this is mandatory! option knitro_options "leastsquares=1 presolve=0"; # Enable Knitro LSQ ## Same problem but this time based on Knitro's least-squares API. # Objective must be constant minimize obj_lsq: 0; # Each residual is a constraint: residual = 0 # s.t. res{i in 1..M}:(alpha[i]-var_alpha)^2 = 0; s.t. res{i in 1..M}: alpha[i] - var_alpha = 0; # Optimize problem using on Knitro LSQ API solve obj_lsq; ``` -------------------------------- ### Knitro Optimization Output with Finite-Difference Gradient Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startR This console output shows the initial results from Knitro when the objective function gradient is approximated using finite-differences. It provides a baseline for comparison with runs where analytical gradients are explicitly provided, highlighting the initial performance metrics. ```Console Output # of gradient evaluations = 0 Total program time (secs) = 0.01465 ( 0.031 CPU time) Time spent in evaluations (secs) = 0.00018 ``` -------------------------------- ### Configure Knitro Environment Variables (Unix Shells) Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/1_introduction/installation/unix Instructions for setting PATH and DYLD_LIBRARY_PATH to include Knitro binaries and libraries, essential for Knitro's operation. This applies to both Bash/sh and csh/tcsh shells, ensuring the system can locate Knitro executables and dynamic libraries. ```bash export PATH= :$PATH export DYLD_LIBRARY_PATH=:$DYLD_LIBRARY_PATH ``` ```csh setenv PATH :$PATH setenv DYLD_LIBRARY_PATH :$DYLD_LIBRARY_PATH ``` -------------------------------- ### Knitro Optimization Output with Analytical Gradient Source: https://www.artelys.com/app/docs/knitro/1_introduction.html/app/docs/knitro/2_userGuide/gettingStarted/startR This console output displays the detailed results of running Knitro with a user-provided analytical gradient. It shows the optimization progress, including iteration count, objective value, error metrics, and final statistics, highlighting the improved convergence and efficiency compared to finite-difference approximation. ```Console Output ======================================= Commercial License Artelys Knitro 14.2.0 ======================================= Knitro presolve eliminated 0 variables and 0 constraints. concurrent_evals: 0 The problem is identified as unconstrained. Problem Characteristics ( Presolved) ----------------------- Objective goal: Minimize Objective type: general Number of variables: 2 ( 2) bounded below only: 0 ( 0) bounded above only: 0 ( 0) bounded below and above: 0 ( 0) fixed: 0 ( 0) free: 2 ( 2) Number of constraints: 0 ( 0) linear equalities: 0 ( 0) quadratic equalities: 0 ( 0) gen. nonlinear equalities: 0 ( 0) linear one-sided inequalities: 0 ( 0) quadratic one-sided inequalities: 0 ( 0) gen. nonlinear one-sided inequalities: 0 ( 0) linear two-sided inequalities: 0 ( 0) quadratic two-sided inequalities: 0 ( 0) gen. nonlinear two-sided inequalities: 0 ( 0) Number of nonzeros in Jacobian: 0 ( 0) Number of nonzeros in Hessian: 0 ( 3) Knitro using the Interior-Point/Barrier Direct algorithm. Iter Objective FeasError OptError ||Step|| CGits -------- -------------- ---------- ---------- ---------- ------- 0 2.420000e+01 0.000e+00 10 1.041833e+00 0.000e+00 3.760e+00 1.537e-01 0 20 6.136281e-02 0.000e+00 9.652e-01 4.395e-02 0 30 5.772274e-08 0.000e+00 3.907e-03 2.378e-03 0 33 2.708220e-22 0.000e+00 2.992e-10 2.089e-07 0 EXIT: Locally optimal solution found. Final Statistics ---------------- Final objective value = 2.70821957121458e-22 Final feasibility error (abs / rel) = 0.00e+00 / 0.00e+00 Final optimality error (abs / rel) = 2.99e-10 / 2.99e-10 # of iterations = 33 # of CG iterations = 4 # of function evaluations = 58 # of gradient evaluations = 34 Total program time (secs) = 0.01170 ( 0.016 CPU time) Time spent in evaluations (secs) = 0.00448 =============================================================================== ```