Knitro / Julia reference

Usage of Knitro.jl is described here.

Introduction to Knitro.jl?

Knitro.jl is the official Julia interface to Knitro. It provides a Julia wrapper to the C API of Knitro, as well as a MathOptInterface bridge to call Knitro from JuMP.

The source code is available in the official github repository.

Installation

The installation of Knitro.jl requires to open a Julia REPL. Then, the following command proceeds to the installation:

julia> ]
pkg> add KNITRO

Note that the environment variable KNITRODIR must be defined and point to the path where Knitro is installed.

Usage

Using Knitro’s API in Julia

Knitro.jl allows to call Knitro directly from Julia. For instance, the following code solves the HS15 non-linear problem with Knitro:

using KNITRO
function callbackEvalF(kc, cb, evalRequest, evalResult, userParams)
    x = evalRequest.x
    # Evaluate nonlinear objective
    dTmp = x[2] - x[1] * x[1]
    evalResult.obj[1] = 100.0 * (dTmp * dTmp) + ((1.0 - x[1]) * (1.0 - x[1]))

    return 0
end

function callbackEvalG!(kc, cb, evalRequest, evalResult, userParams)
    x = evalRequest.x

    # Evaluate gradient of nonlinear objective
    dTmp = x[2] - x[1] * x[1]
    evalResult.objGrad[1] = (-400.0 * dTmp * x[1]) - (2.0 * (1.0 - x[1]))
    evalResult.objGrad[2] = 200.0 * dTmp

    return 0
end

# Create a new Knitro solver instance.
kc = KNITRO.KN_new()

n = 2
KNITRO.KN_add_vars(kc, n, C_NULL)
KNITRO.KN_set_var_lobnds(kc,  [-KNITRO.KN_INFINITY, -KNITRO.KN_INFINITY]) # not necessary since infinite
KNITRO.KN_set_var_upbnds(kc,  [0.5, KNITRO.KN_INFINITY])
# Define an initial point.  If not set, Knitro will generate one.
KNITRO.KN_set_var_primal_init_values(kc, [-2.0, 1.0])

# Add the constraints and set their lower bounds
m = 2
KNITRO.KN_add_cons(kc, m, C_NULL)
KNITRO.KN_set_con_lobnds(kc, [1.0, 0.0])

# First load quadratic structure x0*x1 for the first constraint
KNITRO.KN_add_con_quadratic_struct_one(kc, 1, 0, Cint[0], Cint[1], [1.0])

# Add linear term x0 in the second constraint
KNITRO.KN_add_con_linear_struct_one(kc, 1, 1, Cint[0], [1.0])

# Add quadratic term x1^2 in the second constraint
KNITRO.KN_add_con_quadratic_struct_one(kc, 1, 1, Cint[1], Cint[1], [1.0])

cb = KNITRO.KN_add_eval_callback(kc, callbackEvalF)
KNITRO.KN_set_cb_grad(kc, cb, callbackEvalG!)
nStatus = KNITRO.KN_solve(kc)

# Delete the Knitro solver instance.
KNITRO.KN_free(kc)

Using Knitro with JuMP

Knitro.jl provides also a MathOptInterface bridge to call Knitro directly from JuMP, an optimization modeling language written in Julia. The syntax is as follow.

using JuMP, KNITRO
model = Model(KNITRO.Optimizer)

initval = [-2., 1.]
@variable(model, x[i=1:2], start=initval[i])
@NLobjective(model, Min, 100*(x[1] - x[2]^2)^2 + (1 - x[1])^2)
@constraint(model, x[1] <= 0.5)
c1 = @constraint(model, x[1] * x[2] >= 1)
c2 = @constraint(model, x[1] + x[2]^2 >= 0)

JuMP.optimize!(model)