1 comment

• Gurobi Staff

To model an optimization problem in Gurobi where the objective function changes based on the value of a variable, you can use a piecewise-linear objective function or introduce auxiliary variables and constraints to handle the different cases. For the problem you've described, you need to handle two cases based on the value of x:

1. When x >= 0, the objective is 2 * x.
2. When x < 0, the objective is -3 * abs(x) - 10.

Here's how you can express this in Gurobi using Python:

from gurobi import *# Create a new modelm = Model("piecewise-linear")# Create variablex = m.addVar(lb=-GRB.INFINITY, name="x")# Auxiliary variablesx_pos = m.addVar(name="x_pos")  # For positive part of xx_neg = m.addVar(name="x_neg")  # For negative part of x# Objective functionm.setObjective(2 * x_pos - 3 * x_neg - 10, GRB.MAXIMIZE)# Add constraintsm.addConstr(x == x_pos - x_neg, "x_split")  # Split x into positive and negative partsm.addConstr(x_pos >= 0, "x_pos_nonneg")m.addConstr(x_neg >= 0, "x_neg_nonneg")# Optimize modelm.optimize()# Print resultif m.status == GRB.OPTIMAL:    print('Optimal value:', m.objVal)    print('x:', x.X)else:    print('No optimal solution found.')

In this code:

• x is your variable that can take any real value.
• x_pos and x_neg are auxiliary variables representing the positive and negative parts of x, respectively.
• The constraint x == x_pos - x_neg splits x into its positive and negative components.
• The objective function is set to maximize 2 * x_pos - 3 * x_neg - 10.
• Finally, the model is solved, and the optimal value of the objective function along with the value of x is printed.

Please replace GRB.MAXIMIZE with GRB.MINIMIZE if you intend to minimize the objective function instead.