nlconstr.py#

#!/usr/bin/env python3

# Copyright 2026, Gurobi Optimization, LLC

# This example formulates and solves the following simple nonlinear model
# using the nonlinear API:
#
#   minimize    x - y
#   subject to  sin(x) * x + x^2 * y  <= 1
#               y = cos(x) (<=> cos(x) - y = 0)
#              -1 <= x <= 2
#               0 <= y <= 2
#
# The example uses the nonlinear expression API. The left-hand sides
# of the constraints are built as NLExpr objects with the overloaded
# operators, the nonlinear functions hosted in gurobipy.nlfunc, and the
# ** operator, and passed directly to addConstr().
#
# We retrieve a nonlinear constraint with getNLConstrLHS() together with
# its sense and rhs attribute and print it.

import gurobipy as gp
from gurobipy import GRB
from gurobipy.nlfunc import sin, cos

# Create new model
model = gp.Model("nlconstr")

# Create variables
x = model.addVar(lb=-1.0, ub=2.0, obj=1.0, vtype=GRB.CONTINUOUS, name="x")
y = model.addVar(lb=0.0, ub=2.0, obj=-1.0, vtype=GRB.CONTINUOUS, name="y")

# Add nonlinear constraint: sin(x)*x + x^2*y <= 1.
nlc1 = model.addConstr(sin(x) * x + x**2 * y <= 1.0, "NonlinearConstraint1")

# Add nonlinear constraint: cos(x) - y = 0
nlc2 = model.addConstr(cos(x) - y == 0.0, "NonlinearConstraint2")

# Optimize model
model.optimize()

print("\nSolving model with nonlinear constraints")
if model.Status == GRB.OPTIMAL:
    print(f"Optimal objective: {model.ObjVal}")
    print(f"  x={x.X}, y={y.X}")
elif model.Status == GRB.INF_OR_UNBD:
    print("Model is infeasible or unbounded")
else:
    print("Optimization was stopped early")

# Retrieve the first nonlinear constraint as an NLExpr and print it
lhs = model.getNLConstrLHS(nlc1)
print(f'\nRetrieved NL constraint: "{lhs} {nlc1.NLCSense}= {nlc1.NLCRHS}"')