'How do I insert the objective function with absolute value in Gurobi using Java language?

My objective function is like min|XyPiy-XkPik| i=1...10, j=1...4, k=5...8

I tried to write the code like this, but I don't know what to do with the module

GRBLinExpr obj = new GRBLinExpr();
for(int y=1; y<=4; y++) {
        for(int i=0; i<10; i++) {
            obj.addTerm(pij[i][y], xij[i][y]);
        }
    }
    for(int k=5; k<=8; k++) {
        for(int i=0; i<10; i++) {
            obj.addTerm(-pij[i][k], xij[i][k]);
        }
    }
    model.setObjective(obj);
    model.set(GRB.IntAttr.ModelSense, GRB.MINIMIZE);

It's one of my first exercises and I don't know how to do it, I hope someone can help me



Solution 1:[1]

You need to add an auxiliary variable that takes the value of the objective term. Then, you can define a new general constraint for the absolute value of this auxiliary variable: GRBModel.addGenConstrAbs

The resultant of this constraint (which is yet another auxiliary variable) can then be put into the objective function to be minimized.

GRBVar objvar = model.addVar(-GRB.INFINITY, GRB.INFINITY, 0.0, GRB.CONTINUOUS);
GRBVar absobj = model.addVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS);
GRBLinExpr obj = new GRBLinExpr();

for(int y=1; y<=4; y++) {
    for(int i=0; i<10; i++) {
        obj.addTerm(pij[i][y], xij[i][y]);
    }
}
for(int k=5; k<=8; k++) {
    for(int i=0; i<10; i++) {
        obj.addTerm(-pij[i][k], xij[i][k]);
    }
}

model.addConstr(objvar, GRB.EQUAL, obj, "obj constraint");
model.addGenConstrAbs(absobj, objvar, "abs obj");

Here, you don't even need to set the objective anymore, because the only objective coefficient is already defined when adding variable absobj (the third argument).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mattmilten