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

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 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.0.0
=======================================

No start point provided -- Knitro computing one.

Knitro presolve eliminated 0 variables and 0 constraints.

concurrent_evals:        0
The problem is identified as an LP.

Problem Characteristics                                 (   Presolved)
-----------------------
Objective goal:  Minimize
Objective type:  linear
Number of variables:                                  4 (           4)
    bounded below only:                               4 (           4)
    bounded above only:                               0 (           0)
    bounded below and above:                          0 (           0)
    fixed:                                            0 (           0)
    free:                                             0 (           0)
Number of constraints:                                2 (           2)
    linear equalities:                                2 (           2)
    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:                       6 (           6)
Number of nonzeros in Hessian:                        0 (           0)

Knitro using the Interior-Point/Barrier Direct algorithm.

Iter      Objective      FeasError   OptError    ||Step||    CGits
--------  --------------  ----------  ----------  ----------  -------
    0   -1.137168e+01   1.787e+00
    5   -1.733333e+01   1.776e-15   7.959e-11   1.334e-05        0

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.045 (     0.000 CPU time)
Time spent in evaluations (secs)    =       0.000

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


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.0.0
=======================================

No start point provided -- Knitro computing one.

Knitro presolve eliminated 0 variables and 0 constraints.

concurrent_evals:        0
The problem is identified as an LP.

Problem Characteristics                                 (   Presolved)
-----------------------
Objective goal:  Minimize
Objective type:  linear
Number of variables:                                  4 (           4)
    bounded below only:                               4 (           4)
    bounded above only:                               0 (           0)
    bounded below and above:                          0 (           0)
    fixed:                                            0 (           0)
    free:                                             0 (           0)
Number of constraints:                                2 (           2)
    linear equalities:                                2 (           2)
    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:                       6 (           6)
Number of nonzeros in Hessian:                        0 (           0)

Knitro using the Interior-Point/Barrier Direct algorithm.

Iter      Objective      FeasError   OptError    ||Step||    CGits
--------  --------------  ----------  ----------  ----------  -------
    0   -1.137168e+01   1.787e+00
    5   -1.733333e+01   1.776e-15   7.959e-11   1.334e-05        0

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.006 (     0.000 CPU time)
Time spent in evaluations (secs)    =       0.000

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

Additional examples

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