Getting started with Python

How to set up the Knitro Python interface ?

The simplest way to set up the Knitro Python interface is to install the knitro Python package. It is available on the standard Python repository PyPI (Python Package Index), you can therefore install it using your preferred Python package manager (pip, Poetry, uv, Hatch, PDM, Rye …). It contains the Knitro binaries as well as the Python interface. In a Python environment which has the knitro package installed, you can either use Knitro through its Python interface (by including import knitro in your Python code), or call the solver from Pyomo with SolverFactory("knitroampl").

In order to use Knitro, you will need a valid license. If you do not yet have one, please visit http://www.artelys.com/knitro in order to obtain a trial license and start using Knitro. To generate a license for you, we often require an Artelys-specific identifier called the “machine-id”. To know your machine-id, the simplest method is to open a Python console in an environment with the Knitro package installed, and run the command: python -c "import knitro; knitro.KN_new()". A message detailing your machine-id will appear near the top of the output.

If you are a legacy user and already have a working setup using Knitro binaries, you might prefer to setup the Python interface locally using your distribution: see section Setting up the Python interface from your Knitro distribution.

How to use the Knitro Python interface ?

You have the option to define your problem from Python using either

  • the knitro.optimize() method in a single call fashion

  • the Python interface of the Knitro callable library

The knitro.optimize() method has the advantage to highly simplify the definition of the problem structure, whereas the callable library gives access to all the functionalities of the C interface defined in knitro.h.

First Python example using the callable library

The following introductory example shows how to solve a simple linear problem presented in exampleLP1.py using the Python interface of the callable library.

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")

# Initialize Knitro with the problem definition.

# Add the variables and set their bounds.
# Note: unset bounds assumed to be infinite.
xIndices = KN_add_vars (kc, 4)
for x in xIndices:
    KN_set_var_lobnds (kc, x, 0.0)

# Add the constraints and set the rhs and coefficients.
KN_add_cons(kc, 2)
KN_set_con_eqbnds (kc, cEqBnds = [5, 8])

# Add Jacobian structure and coefficients.
# First constraint
jacIndexCons = [0, 0, 0]
jacIndexVars = [0, 1, 2]
jacCoefs = [1.0, 1.0, 1.0]
# Second constraint
jacIndexCons += [1, 1, 1]
jacIndexVars += [0, 1, 3]
jacCoefs += [2.0, 0.5, 1.0]
KN_add_con_linear_struct (kc, jacIndexCons, jacIndexVars, jacCoefs)

# Set minimize or maximize (if not set, assumed minimize).
KN_set_obj_goal (kc, KN_OBJGOAL_MINIMIZE)

# Set the coefficients for the objective.
objIndices = [0, 1]
objCoefs = [-4.0, -2.0]
KN_add_obj_linear_struct (kc, objIndices, objCoefs)

# Solve the problem.
# Return status codes are defined in "knitro.py" and described in the Knitro manual.
nStatus = KN_solve (kc)
print ("Knitro converged with final status = %d" % nStatus)

# An example of obtaining solution information.
nStatus, objSol, x, lambda_ =  KN_get_solution (kc)
print ("  optimal objective value  = %e" % objSol)
print ("  optimal primal values x  = (%e, %e, %e, %e)" % (x[0], x[1], x[2], x[3]))
print ("  feasibility violation    = %e" % KN_get_abs_feas_error (kc))
print ("  KKT optimality violation = %e" % KN_get_abs_opt_error (kc))

# Delete the Knitro solver instance.
KN_free (kc)

Knitro returns the following output:

=======================================
         Commercial License
        Artelys Knitro 15.1.0
=======================================

No start point provided -- Knitro computing one.

Knitro presolve eliminated 0 variables and 0 constraints.

concurrent_evals:        0
feastol                  1e-06
feastol_abs              0.001
opttol                   1e-06
opttol_abs               0.001
Knitro running advanced initialization strategy specified by initpt_strategy.

Problem Characteristics                     |           Presolved
-----------------------
Problem type: LP
Objective: minimize / linear
Number of variables:                      4 |                             4
  bounds:         lower     upper     range |     lower     upper     range
                      4         0         0 |         4         0         0
                             free     fixed |                free     fixed
                                0         0 |                   0         0
Number of constraints:                    2 |                             2
                    eq.     ineq.     range |       eq.     ineq.     range
                      2         0         0 |         2         0         0
Number of nonzeros:     objective  Jacobian |           objective  Jacobian
                                2         6 |                   2         6
Coefficient range:
  linear objective:          [2e+00, 4e+00] |                [2e+00, 4e+00]
  linear constraints:        [5e-01, 2e+00] |                [5e-01, 2e+00]
  variable bounds:           [0e+00, 0e+00] |                [0e+00, 0e+00]
  constraint bounds:         [5e+00, 8e+00] |                [5e+00, 8e+00]

Knitro using the Interior-Point/Barrier Direct algorithm.

    Iter       Objective  FeasError   OptError   ||Step||      Time
--------  --------------  ---------  ---------  ---------  --------
       0   -8.539167e+00   2.15e-01
       5   -1.733333e+01   1.77e-15   7.96e-11   1.33e-05      0.03

EXIT: Optimal solution found.

Final Statistics
----------------
Final objective value               =  -1.73333333331683e+01
Final feasibility error (abs / rel) =   1.78e-15 / 9.94e-16
Final optimality error  (abs / rel) =   7.96e-11 / 1.99e-11
# of iterations                     =          5
# of CG iterations                  =          0
# of function evaluations           =          0
# of gradient evaluations           =          0
# of Hessian evaluations            =          0
Total program time (secs)           =       0.03485 (     0.024 CPU time)
Time spent in evaluations (secs)    =       0.00000

===============================================================================


Knitro converged with final status = 0
optimal objective value  = -1.733333e+01
optimal primal values x  = (3.666667e+00, 1.333333e+00, 7.958766e-11, 4.420776
feasibility violation    = 1.776357e-15
KKT optimality violation = 7.958766e-11

First Python example using the knitro.optimize() method

The following introductory example shows how to solve a simple linear problem presented in exampleLP1.py using the knitro.optimize() method in a single call fashion.

from knitro import *

# Define the variables information
variables = Variables(nV=4, xLoBnds=[0,0,0,0])

# Define the objective information
# Default objGoal is set to 'minimize'
objective = Objective(objLinear=[[0, 1], [-4, -2]])

# Define the constraints information
constraints = Constraints(nC=2,
                          cLinear=[[0, 0, 0, 1, 1, 1],
                                   [0, 1, 2, 0, 1, 3],
                                   [1., 1., 1., 2., 0.5, 1.]],
                          cEqBnds=[5., 8.])

# Solve the problem
solution = optimize(variables=variables,
                    objective=objective,
                    constraints=constraints)

Knitro returns the following output:

=======================================
         Commercial License
        Artelys Knitro 15.1.0
=======================================

No start point provided -- Knitro computing one.

Knitro presolve eliminated 0 variables and 0 constraints.

concurrent_evals:        0
feastol                  1e-06
feastol_abs              0.001
opttol                   1e-06
opttol_abs               0.001
Knitro running advanced initialization strategy specified by initpt_strategy.

Problem Characteristics                     |           Presolved
-----------------------
Problem type: LP
Objective: minimize / linear
Number of variables:                      4 |                             4
  bounds:         lower     upper     range |     lower     upper     range
                      4         0         0 |         4         0         0
                             free     fixed |                free     fixed
                                0         0 |                   0         0
Number of constraints:                    2 |                             2
                    eq.     ineq.     range |       eq.     ineq.     range
                      2         0         0 |         2         0         0
Number of nonzeros:     objective  Jacobian |           objective  Jacobian
                                2         6 |                   2         6
Coefficient range:
  linear objective:          [2e+00, 4e+00] |                [2e+00, 4e+00]
  linear constraints:        [5e-01, 2e+00] |                [5e-01, 2e+00]
  variable bounds:           [0e+00, 0e+00] |                [0e+00, 0e+00]
  constraint bounds:         [5e+00, 8e+00] |                [5e+00, 8e+00]

Knitro using the Interior-Point/Barrier Direct algorithm.

    Iter       Objective  FeasError   OptError   ||Step||      Time
--------  --------------  ---------  ---------  ---------  --------
       0   -8.539167e+00   2.15e-01
       5   -1.733333e+01   1.77e-15   7.95e-11   1.33e-05      0.00

EXIT: Optimal solution found.

Final Statistics
----------------
Final objective value               =  -1.73333333331683e+01
Final feasibility error (abs / rel) =   1.78e-15 / 9.94e-16
Final optimality error  (abs / rel) =   7.96e-11 / 1.99e-11
# of iterations                     =          5
# of CG iterations                  =          0
# of function evaluations           =          0
# of gradient evaluations           =          0
# of Hessian evaluations            =          0
Total program time (secs)           =       0.00627 (     0.006 CPU time)
Time spent in evaluations (secs)    =       0.00000

===============================================================================

Additional examples

More examples using the Python interface are provided in the Python/examples directory of the Knitro distribution.