It is sometimes necessary to query a constraint's left-hand side (LHS). Use cases include:
- Printing a constraint definition to verify it is written correctly
- Evaluating a constraint's LHS at the current solution
- Changing coefficients on the constraint's LHS
You can access the Sense and right-hand side (RHS) of a linear constraint by querying the corresponding constraint attributes. The left-hand side or linear expression of the constraint can be accessed via:
- Model.getRow() in Python
- GRBModel::getRow() in C++
- GRBModel.getRow() in Java
- GRBModel.GetRow() in .NET
Printing a constraint definition
The following Python code prints the definition (LHS, sense, and RHS) of a constraint:
import gurobipy as gp
model = gp.Model()
x = model.addVars(5, name="x")
con = model.addConstr(x.sum() <= 1, name="con1")
model.update()
print(f"{model.getRow(con)} {con.Sense} {con.RHS}")
The output:
x[0] + x[1] + x[2] + x[3] + x[4] < 1.0
Note that it is not sufficient to simply print the Constr object itself; this displays no information other than the name of the constraint.
Evaluating a constraint's LHS at the current solution
The following functions/properties return the value of a linear expression evaluated at the current solution:
- LinExpr.getValue() in Python
- GRBLinExpr::getValue() in C++
- GRBLinExpr.getValue() in Java
- GRBLinExpr.Value in .NET
Thus, in Python, the LHS of a constraint can be computed at the current solution as follows:
import gurobipy as gp
m = gp.read("glass4.mps")
m.optimize()
con = m.getConstrs()[0]
print(m.getRow(con).getValue())
Note that the LHS can only be evaluated at the current solution if Gurobi found at least one feasible solution when optimizing the model.
Changing coefficients on the constraint's LHS
After querying the constraint's left-hand side, you can iterate over the variables and coefficients contained in this linear expression. For example, the following Python script uses the LinExpr.getCoeff(), LinExpr.getVar(), and Model.chgCoeff() methods to increase the coefficients of all variables participating in the model's first constraint by 1:
import gurobipy as gp
m = gp.read("glass4.mps")
con = m.getConstrs()[0]
lexpr = m.getRow(con)
for i in range(lexpr.size()):
coeff = lexpr.getCoeff(i)
v = lexpr.getVar(i)
m.chgCoeff(con, v, coeff + 1)
Analogous functions in other object-oriented APIs are:
Comments
0 comments
Article is closed for comments.