Getting started with Python

The Knitro interface for Python is provided with your Knitro distribution as a Python package. To install Knitro-Python, please ensure that the Knitro dll/library can be dynamically loaded.

Windows

Make sure the Knitro lib directory is specified in the PATH environment variable.

Linux

Make sure the Knitro lib directory is specified in the LD_LIBRARY_PATH environment variable. To do this permanently, open the current user’s profile into a text editor with command line:

vi .bashrc

Add the following export command to your bashrc with the appropriate path:

export LD_LIBRARY_PATH=/path/to/knitrodirectory/lib

Save your changes. To immediately apply changes to bashrc, use the command:

source .bashrc

Mac OS X

Make sure the Knitro directory is specified in the KNITRODIR environment variable. To do this permanently, open the current user’s profile into a text editor with command line:

vi ~/.bash_profile

Add the following export command to your bash_profile with the appropriate path:

export KNITRODIR=/path/to/knitrodirectory

Save your changes. To immediately apply changes to bash_profile, use the command:

source ~/.bash_profile

Once the system’s path correctly set, run the following command in the Python directory of your Knitro distribution:

python setup.py install

You might need to run this command as administrator. We higly recommend using Python’s virtual environment to avoid mixing up with the Python install used by the system.

Run examples

You can now open a Terminal in the Python/examples folder and type:

python example*.py

where example*.py is the name of the Python model you want to run.

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 14.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 14.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.