Nlobj Examples#
This section includes source code for all of the Gurobi nlobj
examples. The same source code can be found in the examples
directory of the Gurobi distribution.
/* Copyright 2026, Gurobi Optimization, LLC */
/* This example formulates and solves the following simple nonlinear model
using the nonlinear objective API:
minimize sin(x) * x + x^2 * y
subject to x + y >= 1
-1 <= x <= 2
0 <= y <= 2
The nonlinear objective is set via GRBsetnlobj() using an expression tree.
Then we retrieve the tree with GRBgetnlobj() and verify it, delete it with
GRBdelnlobj(), replace it with a simple linear objective, and re-optimize.
*/
#include <stdlib.h>
#include <stdio.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
/* Variable data: x (index 0), y (index 1) */
double lb[2] = {-1.0, 0.0};
double ub[2] = { 2.0, 2.0};
char *varnames[2] = {"x", "y"};
/* Expression tree for sin(x) * x + x^2 * y (10 nodes)
*
* node 0: PLUS (root)
* node 1: MULTIPLY (child of 0) -> sin(x) * x
* node 2: SIN (child of 1)
* node 3: VARIABLE x (child of 2)
* node 4: VARIABLE x (child of 1)
* node 5: MULTIPLY (child of 0) -> x^2 * y
* node 6: POW (child of 5)
* node 7: VARIABLE x (child of 6)
* node 8: CONSTANT 2 (child of 6)
* node 9: VARIABLE y (child of 5)
*/
int nnodes = 10;
int opcode[10] = {GRB_OPCODE_PLUS, /* 0: root */
GRB_OPCODE_MULTIPLY, /* 1: sin(x)*x */
GRB_OPCODE_SIN, /* 2: sin(...) */
GRB_OPCODE_VARIABLE, /* 3: x */
GRB_OPCODE_VARIABLE, /* 4: x */
GRB_OPCODE_MULTIPLY, /* 5: x^2 * y */
GRB_OPCODE_POW, /* 6: x^2 */
GRB_OPCODE_VARIABLE, /* 7: x */
GRB_OPCODE_CONSTANT, /* 8: 2.0 */
GRB_OPCODE_VARIABLE}; /* 9: y */
double data[10] = {-1.0, -1.0, -1.0,
0.0, /* x index */
0.0, /* x index */
-1.0, -1.0,
0.0, /* x index */
2.0,
1.0}; /* y index */
int parent[10] = {-1, 0, 1, 2, 1, 0, 5, 6, 6, 5};
/* Data for querying solution and NL objective */
double sol[2];
int optimstatus;
double objval;
int nnodes_out;
double linobj[2];
/* Create environment */
error = GRBloadenv(&env, "nlobj.log");
if (error) goto QUIT;
/* Create model with two variables, no linear objective */
error = GRBnewmodel(env, &model, "nlobj", 2, NULL, lb, ub, NULL,
varnames);
if (error) goto QUIT;
/* Add constraint: x + y >= 1 */
{
int cind[2] = {0, 1};
double cval[2] = {1.0, 1.0};
error = GRBaddconstr(model, 2, cind, cval, GRB_GREATER_EQUAL, 1.0, "c0");
if (error) goto QUIT;
}
/* Set nonlinear objective */
error = GRBsetnlobj(model, nnodes, opcode, data, parent);
if (error) goto QUIT;
/* Optimize model */
error = GRBoptimize(model);
if (error) goto QUIT;
/* Capture solution information */
error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
if (error) goto QUIT;
printf("\nFirst solve (nonlinear objective)\n");
if (optimstatus == GRB_OPTIMAL) {
error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
if (error) goto QUIT;
error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, 2, sol);
if (error) goto QUIT;
printf("Optimal objective: %.4e\n", objval);
printf(" x=%.6f, y=%.6f\n", sol[0], sol[1]);
} else if (optimstatus == GRB_INF_OR_UNBD) {
printf("Model is infeasible or unbounded\n");
} else {
printf("Optimization was stopped early\n");
}
/* Retrieve the nonlinear objective and print the number of nodes */
error = GRBgetnlobj(model, &nnodes_out, NULL, NULL, NULL);
if (error) goto QUIT;
printf("\nRetrieved NL objective with %d nodes\n", nnodes_out);
/* Delete the nonlinear objective */
error = GRBdelnlobj(model);
if (error) goto QUIT;
printf("Deleted nonlinear objective\n");
/* Set a simple linear objective instead: minimize x + y */
linobj[0] = 1.0;
linobj[1] = 1.0;
error = GRBsetdblattrarray(model, GRB_DBL_ATTR_OBJ, 0, 2, linobj);
if (error) goto QUIT;
/* Re-optimize */
error = GRBoptimize(model);
if (error) goto QUIT;
error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
if (error) goto QUIT;
printf("\nSecond solve (linear objective)\n");
if (optimstatus == GRB_OPTIMAL) {
error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
if (error) goto QUIT;
error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, 2, sol);
if (error) goto QUIT;
printf("Optimal objective: %.4e\n", objval);
printf(" x=%.6f, y=%.6f\n", sol[0], sol[1]);
} else if (optimstatus == GRB_INF_OR_UNBD) {
printf("Model is infeasible or unbounded\n");
} else {
printf("Optimization was stopped early\n");
}
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
/* Copyright 2026, Gurobi Optimization, LLC */
/* This example formulates and solves the following simple
nonlinear model using the nonlinear objective API:
minimize sin(x) * x + x^2 * y
subject to x + y >= 1
-1 <= x <= 2
0 <= y <= 2
The nonlinear objective is set via setNLObj() using an
expression tree. Then we retrieve the tree with getNLObj() and
verify it, delete it with delNLObj(), replace it with a simple
linear objective, and re-optimize.
*/
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
try {
/* Create an environment */
GRBEnv env = GRBEnv("nlobj.log");
/* Create an empty model */
GRBModel model = GRBModel(env);
/* Create variables */
GRBVar x = model.addVar(-1.0, 2.0, 0.0, GRB_CONTINUOUS, "x");
GRBVar y = model.addVar(0.0, 2.0, 0.0, GRB_CONTINUOUS, "y");
/* Add constraint : x + y >= 1 */
model.addConstr(x + y >= 1, "c0");
/* Build the nonlinear objective: sin(x) * x + x^2 * y
*
* Expression tree (7 nodes):
*
* node 0: PLUS (root)
* node 1: MULTIPLY (child of 0) -> sin(x) * x
* node 2: SIN (child of 1)
* node 3: VARIABLE x (child of 2)
* node 4: VARIABLE x (child of 1)
* node 5: MULTIPLY (child of 0) -> x^2 * y
* node 6: POW (child of 5)
* node 7: VARIABLE x (child of 6)
* node 8: CONSTANT 2 (child of 6)
* node 9: VARIABLE y (child of 5)
*/
int nnodes = 10;
int opcode[10] = { GRB_OPCODE_PLUS, /* 0: root */
GRB_OPCODE_MULTIPLY, /* 1: sin(x)*x */
GRB_OPCODE_SIN, /* 2: sin(...) */
GRB_OPCODE_VARIABLE, /* 3: x */
GRB_OPCODE_VARIABLE, /* 4: x */
GRB_OPCODE_MULTIPLY, /* 5: x^2 * y */
GRB_OPCODE_POW, /* 6: x^2 */
GRB_OPCODE_VARIABLE, /* 7: x */
GRB_OPCODE_CONSTANT, /* 8: 2.0 */
GRB_OPCODE_VARIABLE }; /* 9: y */
double data[10] = { -1.0,
-1.0,
-1.0,
(double)x.index(),
(double)x.index(),
-1.0,
-1.0,
(double)x.index(),
2.0,
(double)y.index() };
int parent[10] = { -1, 0, 1, 2, 1, 0, 5, 6, 6, 5 };
/* Set nonlinear objective (minimize by default) */
model.setNLObj(nnodes, opcode, data, parent);
/* Optimize model */
model.optimize();
int status = model.get(GRB_IntAttr_Status);
if (status == GRB_OPTIMAL) {
cout << "First solve (nonlinear objective):" << endl;
cout << " x = " << x.get(GRB_DoubleAttr_X) << endl;
cout << " y = " << y.get(GRB_DoubleAttr_X) << endl;
cout
<< " Obj = "
<< model.get(GRB_DoubleAttr_ObjVal)
<< endl;
}
/* Retrieve the nonlinear objective and verify the number of
nodes */
int nnodes_out = -1 ;
model.getNLObj(&nnodes_out, NULL, NULL, NULL);
cout
<< "\nRetrieved NL objective with "
<< nnodes_out
<< " nodes"
<< endl;
/* Delete the nonlinear objective */
model.delNLObj();
cout << "Deleted nonlinear objective" << endl;
/* Set a simple linear objective instead : minimize x + y */
model.setObjective(x + y);
/* Re-optimize */
model.optimize();
status = model.get(GRB_IntAttr_Status);
if (status == GRB_OPTIMAL) {
cout << "\nSecond solve (linear objective):" << endl;
cout << " x = " << x.get(GRB_DoubleAttr_X) << endl;
cout << " y = " << y.get(GRB_DoubleAttr_X) << endl;
cout
<< " Obj = "
<< model.get(GRB_DoubleAttr_ObjVal)
<< endl;
}
} catch (GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Exception during optimization" << endl;
}
return 0;
}
// Copyright 2026, Gurobi Optimization, LLC
// This example formulates and solves the following simple nonlinear model
// using the nonlinear objective API:
//
// minimize sin(x) * x + x^2 * y
// subject to x + y >= 1
// -1 <= x <= 2
// 0 <= y <= 2
//
// The example is split into two functions that show two ways to build a
// nonlinear objective with the new NL API:
//
// - nlobjNLAPI(): uses the nonlinear expression API. The nonlinear
// objective is built as a GRBNLExpr object with the overloaded
// operators, the nonlinear functions hosted on GRBNLExpr, and the Pow()
// helper, and passed directly to SetNLObj().
//
// - nlobjNLAPIAdv(): uses the advanced expression-tree variant of
// SetNLObj(), where the nonlinear expression is described
// with arrays of opcodes, data, and parent pointers.
//
// In both cases we retrieve the nonlinear objective with GetNLObj(),
// delete it with DelNLObj(), replace it with a simple linear objective, and
// re-optimize.
using System;
using Gurobi;
using static Gurobi.GRBNLExpr;
class nlobj_cs
{
/// <summary>
/// Run both ways of building nonlinear objectives: the nonlinear
/// expression API and the advanced expression-tree API.
/// </summary>
static void Main()
{
try {
// First, the nonlinear expression API
nlobjNLAPI();
// Then, the advanced expression-tree API
nlobjNLAPIAdv();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
/// <summary>
/// Formulate the nonlinear objective with the nonlinear expression API,
/// passing a GRBNLExpr object to SetNLObj().
/// </summary>
static void nlobjNLAPI()
{
// Create environment
GRBEnv env = new GRBEnv("nlobj.log");
// Create empty model
GRBModel model = new GRBModel(env);
// Create variables
GRBVar x = model.AddVar(-1.0, 2.0, 0.0, GRB.CONTINUOUS, "x");
GRBVar y = model.AddVar( 0.0, 2.0, 0.0, GRB.CONTINUOUS, "y");
// Add constraint: x + y >= 1
model.AddConstr(x + y, GRB.GREATER_EQUAL, 1.0, "c0");
// Add nonlinear objective: sin(x)*x + x^2*y <= 1.
// The nonlinear expression is built as a GRBNLExpr:
// GRBNLExpr.Sin(x) -> sin(x)
// GRBNLExpr.Pow(x, 2.0) -> x^2 (a SQUARE node)
model.SetNLObj(Sin(x) * x + Pow(x, 2.0) * y);
// Optimize model
model.Optimize();
Console.WriteLine("\nFirst solve (nonlinear objective)");
if (model.Status == GRB.Status.OPTIMAL) {
Console.WriteLine("Optimal objective: {0:E4}", model.ObjVal);
Console.WriteLine(" x={0:F6}, y={1:F6}", x.X, y.X);
} else {
Console.WriteLine("Optimization did not produce an optimal solution");
}
// Retrieve the nonlinear objective and print the number of nodes
GRBNLExpr nlobj = model.GetNLObj();
Console.WriteLine("\nRetrieved NL objective: \"" + nlobj + "\"");
// Delete the nonlinear objective
model.DelNLObj();
Console.WriteLine("Deleted nonlinear objective");
// Set a simple linear objective instead: minimize x + y
model.SetObjective(x + y, GRB.MINIMIZE);
// Re-optimize
model.Optimize();
Console.WriteLine("\nSecond solve (linear objective)");
if (model.Status == GRB.Status.OPTIMAL) {
Console.WriteLine("Optimal objective: {0:E4}", model.ObjVal);
Console.WriteLine(" x={0:F6}, y={1:F6}", x.X, y.X);
} else {
Console.WriteLine("Optimization did not produce an optimal solution");
}
// Dispose of model and env
model.Dispose();
env.Dispose();
}
/// <summary>
/// Formulate the nonlinear objective with the advanced expression-tree
/// variant of SetNLObj(), where the nonlinear expression is
/// described with arrays of opcodes, data, and parent pointers.
/// </summary>
static void nlobjNLAPIAdv()
{
// Create environment
GRBEnv env = new GRBEnv("nlobj.log");
// Create empty model
GRBModel model = new GRBModel(env);
// Create variables
GRBVar x = model.AddVar(-1.0, 2.0, 0.0, GRB.CONTINUOUS, "x");
GRBVar y = model.AddVar( 0.0, 2.0, 0.0, GRB.CONTINUOUS, "y");
// Add constraint: x + y >= 1
model.AddConstr(x + y, GRB.GREATER_EQUAL, 1.0, "c0");
// Expression tree for sin(x) * x + x^2 * y (10 nodes)
//
// node 0: PLUS (root)
// node 1: MULTIPLY (child of 0) -> sin(x) * x
// node 2: SIN (child of 1)
// node 3: VARIABLE x (child of 2)
// node 4: VARIABLE x (child of 1)
// node 5: MULTIPLY (child of 0) -> x^2 * y
// node 6: POW (child of 5)
// node 7: VARIABLE x (child of 6)
// node 8: CONSTANT 2 (child of 6)
// node 9: VARIABLE y (child of 5)
int[] opcode = new int[] {
GRB.OPCODE_PLUS,
GRB.OPCODE_MULTIPLY,
GRB.OPCODE_SIN,
GRB.OPCODE_VARIABLE,
GRB.OPCODE_VARIABLE,
GRB.OPCODE_MULTIPLY,
GRB.OPCODE_POW,
GRB.OPCODE_VARIABLE,
GRB.OPCODE_CONSTANT,
GRB.OPCODE_VARIABLE
};
double[] data = new double[] {
-1.0, -1.0, -1.0,
x.Index,
x.Index,
-1.0, -1.0,
x.Index,
2.0,
y.Index
};
int[] parent = new int[] {-1, 0, 1, 2, 1, 0, 5, 6, 6, 5};
// Set nonlinear objective
model.SetNLObj(opcode, data, parent);
// Optimize model
model.Optimize();
Console.WriteLine("\nFirst solve (nonlinear objective)");
if (model.Status == GRB.Status.OPTIMAL) {
Console.WriteLine("Optimal objective: {0:E4}", model.ObjVal);
Console.WriteLine(" x={0:F6}, y={1:F6}", x.X, y.X);
} else {
Console.WriteLine("Optimization did not produce an optimal solution");
}
// Retrieve the nonlinear objective and print the number of nodes
int nnodes;
model.GetNLObj(out nnodes, null, null, null);
Console.WriteLine("\nRetrieved NL objective with " + nnodes + " nodes");
// Delete the nonlinear objective
model.DelNLObj();
Console.WriteLine("Deleted nonlinear objective");
// Set a simple linear objective instead: minimize x + y
model.SetObjective(x + y, GRB.MINIMIZE);
// Re-optimize
model.Optimize();
Console.WriteLine("\nSecond solve (linear objective)");
if (model.Status == GRB.Status.OPTIMAL) {
Console.WriteLine("Optimal objective: {0:E4}", model.ObjVal);
Console.WriteLine(" x={0:F6}, y={1:F6}", x.X, y.X);
} else {
Console.WriteLine("Optimization did not produce an optimal solution");
}
// Dispose of model and env
model.Dispose();
env.Dispose();
}
}
/* Copyright 2026, Gurobi Optimization, LLC */
/* This example formulates and solves the following simple nonlinear model
using the nonlinear objective API:
minimize sin(x) * x + x^2 * y
subject to x + y >= 1
-1 <= x <= 2
0 <= y <= 2
The nonlinear objective is set via setNLObj() using an expression tree.
Then we retrieve the tree with getNLObj() and verify it, delete it with
delNLObj(), replace it with a simple linear objective, and re-optimize.
*/
import com.gurobi.gurobi.*;
public class NLObj {
public static void main(String[] args) {
try {
// Create environment
GRBEnv env = new GRBEnv("nlobj.log");
// Create empty model
GRBModel model = new GRBModel(env);
// Create variables
GRBVar x = model.addVar(-1.0, 2.0, 0.0, GRB.CONTINUOUS, "x");
GRBVar y = model.addVar( 0.0, 2.0, 0.0, GRB.CONTINUOUS, "y");
// Add constraint: x + y >= 1
GRBLinExpr expr = new GRBLinExpr();
expr.addTerm(1.0, x);
expr.addTerm(1.0, y);
model.addConstr(expr, GRB.GREATER_EQUAL, 1.0, "c0");
/* Expression tree for sin(x) * x + x^2 * y (10 nodes)
*
* node 0: PLUS (root)
* node 1: MULTIPLY (child of 0) -> sin(x) * x
* node 2: SIN (child of 1)
* node 3: VARIABLE x (child of 2)
* node 4: VARIABLE x (child of 1)
* node 5: MULTIPLY (child of 0) -> x^2 * y
* node 6: POW (child of 5)
* node 7: VARIABLE x (child of 6)
* node 8: CONSTANT 2 (child of 6)
* node 9: VARIABLE y (child of 5)
*/
int[] opcode = new int[] {
GRB.OPCODE_PLUS, // 0: root
GRB.OPCODE_MULTIPLY, // 1: sin(x)*x
GRB.OPCODE_SIN, // 2: sin(...)
GRB.OPCODE_VARIABLE, // 3: x
GRB.OPCODE_VARIABLE, // 4: x
GRB.OPCODE_MULTIPLY, // 5: x^2 * y
GRB.OPCODE_POW, // 6: x^2
GRB.OPCODE_VARIABLE, // 7: x
GRB.OPCODE_CONSTANT, // 8: 2.0
GRB.OPCODE_VARIABLE // 9: y
};
double[] data = new double[] {
-1.0, -1.0, -1.0,
x.index(), // x index
x.index(), // x index
-1.0, -1.0,
x.index(), // x index
2.0,
y.index() // y index
};
int[] parent = new int[] {-1, 0, 1, 2, 1, 0, 5, 6, 6, 5};
// Set nonlinear objective
model.setNLObj(opcode, data, parent);
// Optimize model
model.optimize();
System.out.println("\nFirst solve (nonlinear objective)");
if (model.get(GRB.IntAttr.Status) == GRB.OPTIMAL) {
System.out.printf("Optimal objective: %.4e%n",
model.get(GRB.DoubleAttr.ObjVal));
System.out.printf(" x=%.6f, y=%.6f%n",
x.get(GRB.DoubleAttr.X),
y.get(GRB.DoubleAttr.X));
} else {
System.out.println("Optimization did not produce an optimal solution");
}
// Retrieve the nonlinear objective and print the number of nodes
int[] nnodes = new int[1];
model.getNLObj(nnodes, null, null, null);
System.out.println("\nRetrieved NL objective with " + nnodes[0] + " nodes");
// Delete the nonlinear objective
model.delNLObj();
System.out.println("Deleted nonlinear objective");
// Set a simple linear objective instead: minimize x + y
GRBLinExpr linobj = new GRBLinExpr();
linobj.addTerm(1.0, x);
linobj.addTerm(1.0, y);
model.setObjective(linobj, GRB.MINIMIZE);
// Re-optimize
model.optimize();
System.out.println("\nSecond solve (linear objective)");
if (model.get(GRB.IntAttr.Status) == GRB.OPTIMAL) {
System.out.printf("Optimal objective: %.4e%n",
model.get(GRB.DoubleAttr.ObjVal));
System.out.printf(" x=%.6f, y=%.6f%n",
x.get(GRB.DoubleAttr.X),
y.get(GRB.DoubleAttr.X));
} else {
System.out.println("Optimization did not produce an optimal solution");
}
// Dispose of model and environment
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
function nlobj()
% Copyright 2026, Gurobi Optimization, LLC
%
% This example formulates and solves the following simple nonlinear model
% using the nonlinear objective API:
%
% minimize
% sin(x) * x + x^2 * y
% subject to
% x + y >= 1
% -1 <= x <= 2
% 0 <= y <= 2
%
% The nonlinear objective is set through the model.nlobj field, which holds
% the expression tree of the objective function.
model.varnames = {'x', 'y'};
% Bounds: -1 <= x <= 2, 0 <= y <= 2
model.lb = [-1; 0];
model.ub = [ 2; 2];
% Add constraint: x + y >= 1
model.A = sparse([1 1]);
model.rhs = 1;
model.sense = '>';
% Set nonlinear objective: sin(x) * x + x^2 * y
%
% The objective is given as an expression tree with 10 nodes. Every node has
% an opcode, a data value, and the index of its parent node. Nodes are
% 1-based, and the root node is marked by a parent of 0. The data value of a
% VARIABLE node is the 1-based index of that variable, the data value of a
% CONSTANT node is the constant itself, and all other nodes use -1.
%
% node 1: PLUS (root)
% node 2: MULTIPLY (child of 1) -> sin(x) * x
% node 3: SIN (child of 2)
% node 4: VARIABLE x (child of 3)
% node 5: VARIABLE x (child of 2)
% node 6: MULTIPLY (child of 1) -> x^2 * y
% node 7: POW (child of 6)
% node 8: VARIABLE x (child of 7)
% node 9: CONSTANT 2 (child of 7)
% node 10: VARIABLE y (child of 6)
model.nlobj.opcode = [ ...
GRB.OPCODE_PLUS, ... % 1: root
GRB.OPCODE_MULTIPLY, ... % 2: sin(x) * x
GRB.OPCODE_SIN, ... % 3: sin(...)
GRB.OPCODE_VARIABLE, ... % 4: x
GRB.OPCODE_VARIABLE, ... % 5: x
GRB.OPCODE_MULTIPLY, ... % 6: x^2 * y
GRB.OPCODE_POW, ... % 7: x^2
GRB.OPCODE_VARIABLE, ... % 8: x
GRB.OPCODE_CONSTANT, ... % 9: 2
GRB.OPCODE_VARIABLE, ... % 10: y
];
model.nlobj.data = [-1, -1, -1, 1, 1, -1, -1, 1, 2, 2];
model.nlobj.parent = [ 0, 1, 2, 3, 2, 1, 6, 7, 7, 6];
% Optimize
params.logfile = 'nlobj.log';
result = gurobi(model, params);
if strcmp(result.status, 'OPTIMAL')
for j = 1:2
fprintf('%s %e\n', model.varnames{j}, result.x(j));
end
fprintf('Obj: %e\n', result.objval);
else
fprintf('Optimization did not produce an optimal solution\n');
end
end
#!/usr/bin/env python3
# Copyright 2026, Gurobi Optimization, LLC
# This example formulates and solves the following simple nonlinear model
# using the nonlinear objective API:
#
# minimize sin(x) * x + x^2 * y
# subject to x + y >= 1
# -1 <= x <= 2
# 0 <= y <= 2
#
# The example uses the nonlinear expression API. The nonlinear
# expression in the objective is built as NLExpr object with the overloaded
# operators, the nonlinear functions hosted in gurobipy.nlfunc, and the
# ** operator.
#
# We retrieve the nonlinear objective with getObjective() and print it.
import gurobipy as gp
from gurobipy import GRB
from gurobipy.nlfunc import sin, cos
# Create new model
model = gp.Model("nlobj")
# Create variables
x = model.addVar(lb=-1.0, ub=2.0, obj=0.0, vtype=GRB.CONTINUOUS, name="x")
y = model.addVar(lb=0.0, ub=2.0, obj=0.0, vtype=GRB.CONTINUOUS, name="y")
# Add constraint: x + y >= 1
model.addConstr(x + y >= 1.0, "c0")
# Add nonlinear objective: sin(x)*x + x^2*y
model.setObjective(sin(x) * x + x**2 * y)
# Optimize model
model.optimize()
print("\nSolving model with nonlinear objective")
if model.Status == GRB.OPTIMAL:
print(f"Optimal objective: {model.ObjVal}")
print(f" x={x.X}, y={y.X}")
else:
print("Optimization did not produce an optimal solution")
# Retrieve the nonlinear objective as an NLExpr and print it
nlobj = model.getObjective()
print(f'\nRetrieved NL objective: "{nlobj}"')
' Copyright 2026, Gurobi Optimization, LLC
'
' This example formulates and solves the following simple nonlinear model
' using the nonlinear objective API:
'
' minimize sin(x) * x + x^2 * y
' subject to x + y >= 1
' -1 <= x <= 2
' 0 <= y <= 2
'
' The example is split into two functions that show two ways to build a
' nonlinear objective with the new NL API:
'
' - nlobjNLAPI(): uses the nonlinear expression API. The nonlinear
' objective is built as a GRBNLExpr object with the overloaded
' operators, the nonlinear functions hosted on GRBNLExpr, and the Pow()
' helper, and passed directly to SetNLObj().
'
' - nlobjNLAPIAdv(): uses the advanced expression-tree variant of
' SetNLObj(), where the nonlinear expression is described
' with arrays of opcodes, data, and parent pointers.
'
' In both cases we retrieve the nonlinear objective with GetNLObj(),
' delete it with DelNLObj(), replace it with a simple linear objective, and
' re-optimize.
Imports System
Imports Gurobi
Class nlobj_vb
' Run both ways of building nonlinear objectives: the nonlinear
' expression API and the advanced expression-tree API.
Shared Sub Main()
Try
' First, the nonlinear expression API
nlobjNLAPI()
' Then, the advanced expression-tree API
nlobjNLAPIAdv()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
' nlobjNLAPI(): formulates the nonlinear objective with the nonlinear
' expression API, passing a GRBNLExpr object to SetNLObj().
Shared Sub nlobjNLAPI()
' Create environment
Dim env As GRBEnv = New GRBEnv("nlobj.log")
' Create empty model
Dim model As GRBModel = New GRBModel(env)
' Create variables
Dim x As GRBVar = model.AddVar(-1.0, 2.0, 0.0, GRB.CONTINUOUS, "x")
Dim y As GRBVar = model.AddVar(0.0, 2.0, 0.0, GRB.CONTINUOUS, "y")
' Add constraint: x + y >= 1
model.AddConstr(x + y, GRB.GREATER_EQUAL, 1.0, "c0")
' Add nonlinear objective: sin(x)*x + x^2*y.
' The nonlinear expression is built as a GRBNLExpr:
' GRBNLExpr.Sin(x) -> sin(x)
' GRBNLExpr.Pow(x, 2.0) -> x^2 (a SQUARE node)
model.SetNLObj(GRBNLExpr.Sin(x) * x + GRBNLExpr.Pow(x, 2.0) * y)
' Optimize model
model.Optimize()
Console.WriteLine("")
Console.WriteLine("First solve (nonlinear objective)")
If model.Status = GRB.Status.OPTIMAL Then
Console.WriteLine("Optimal objective: " & model.ObjVal.ToString("E4"))
Console.WriteLine(" x=" & x.X.ToString("F6") & _
", y=" & y.X.ToString("F6"))
Else
Console.WriteLine("Optimization did not produce an optimal solution")
End If
' Retrieve the nonlinear objective as a GRBNLExpr and print it
Dim nlobj As GRBNLExpr = model.GetNLObj()
Console.WriteLine("")
Console.WriteLine("Retrieved NL objective: """ & nlobj.ToString() & """")
' Delete the nonlinear objective
model.DelNLObj()
Console.WriteLine("Deleted nonlinear objective")
' Set a simple linear objective instead: minimize x + y
model.SetObjective(x + y, GRB.MINIMIZE)
' Re-optimize
model.Optimize()
Console.WriteLine("")
Console.WriteLine("Second solve (linear objective)")
If model.Status = GRB.Status.OPTIMAL Then
Console.WriteLine("Optimal objective: " & model.ObjVal.ToString("E4"))
Console.WriteLine(" x=" & x.X.ToString("F6") & _
", y=" & y.X.ToString("F6"))
Else
Console.WriteLine("Optimization did not produce an optimal solution")
End If
' Dispose of model and env
model.Dispose()
env.Dispose()
End Sub
' nlobjNLAPIAdv(): formulates the nonlinear objective with the advanced
' expression-tree variant of SetNLObj(), where the nonlinear expression
' is described with arrays of opcodes, data, and parent pointers.
Shared Sub nlobjNLAPIAdv()
' Create environment
Dim env As GRBEnv = New GRBEnv("nlobj.log")
' Create empty model
Dim model As GRBModel = New GRBModel(env)
' Create variables
Dim x As GRBVar = model.AddVar(-1.0, 2.0, 0.0, GRB.CONTINUOUS, "x")
Dim y As GRBVar = model.AddVar(0.0, 2.0, 0.0, GRB.CONTINUOUS, "y")
' Add constraint: x + y >= 1
model.AddConstr(x + y, GRB.GREATER_EQUAL, 1.0, "c0")
' Expression tree for sin(x) * x + x^2 * y (10 nodes)
'
' node 0: PLUS (root)
' node 1: MULTIPLY (child of 0) -> sin(x) * x
' node 2: SIN (child of 1)
' node 3: VARIABLE x (child of 2)
' node 4: VARIABLE x (child of 1)
' node 5: MULTIPLY (child of 0) -> x^2 * y
' node 6: POW (child of 5)
' node 7: VARIABLE x (child of 6)
' node 8: CONSTANT 2 (child of 6)
' node 9: VARIABLE y (child of 5)
Dim opcode As Integer() = New Integer() { _
GRB.OPCODE_PLUS, _
GRB.OPCODE_MULTIPLY, _
GRB.OPCODE_SIN, _
GRB.OPCODE_VARIABLE, _
GRB.OPCODE_VARIABLE, _
GRB.OPCODE_MULTIPLY, _
GRB.OPCODE_POW, _
GRB.OPCODE_VARIABLE, _
GRB.OPCODE_CONSTANT, _
GRB.OPCODE_VARIABLE _
}
Dim data As Double() = New Double() { _
-1.0, -1.0, -1.0, _
x.Index, _
x.Index, _
-1.0, -1.0, _
x.Index, _
2.0, _
y.Index _
}
Dim parent As Integer() = New Integer() {-1, 0, 1, 2, 1, 0, 5, 6, 6, 5}
' Set nonlinear objective
model.SetNLObj(opcode, data, parent)
' Optimize model
model.Optimize()
Console.WriteLine("")
Console.WriteLine("First solve (nonlinear objective)")
If model.Status = GRB.Status.OPTIMAL Then
Console.WriteLine("Optimal objective: " & model.ObjVal.ToString("E4"))
Console.WriteLine(" x=" & x.X.ToString("F6") & _
", y=" & y.X.ToString("F6"))
Else
Console.WriteLine("Optimization did not produce an optimal solution")
End If
' Retrieve the nonlinear objective and print the number of nodes
Dim nnodes As Integer
model.GetNLObj(nnodes, Nothing, Nothing, Nothing)
Console.WriteLine("")
Console.WriteLine("Retrieved NL objective with " & nnodes & " nodes")
' Delete the nonlinear objective
model.DelNLObj()
Console.WriteLine("Deleted nonlinear objective")
' Set a simple linear objective instead: minimize x + y
model.SetObjective(x + y, GRB.MINIMIZE)
' Re-optimize
model.Optimize()
Console.WriteLine("")
Console.WriteLine("Second solve (linear objective)")
If model.Status = GRB.Status.OPTIMAL Then
Console.WriteLine("Optimal objective: " & model.ObjVal.ToString("E4"))
Console.WriteLine(" x=" & x.X.ToString("F6") & _
", y=" & y.X.ToString("F6"))
Else
Console.WriteLine("Optimization did not produce an optimal solution")
End If
' Dispose of model and env
model.Dispose()
env.Dispose()
End Sub
End Class