Search code examples
c++optimizationgurobimixed-integer-programming

how to access Gurobi variable attributes before optimizing model


I wanted to check variable name, upper bound and lower bound before calling optimize() method in gurobi. When i tried this its giving me error.But same is working fine if called after optimize method.

In below code: First "x.get(GRB_StringAttr_VarName)" is not working which i called before optimize(). Where second "x.get(GRB_StringAttr_VarName)" is working fine. For my work i need to call get name and upper bound before optimize method. Please help

    GRBEnv env = GRBEnv();

    GRBModel model = GRBModel(env);

    // Create variables

    GRBVar x = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "x");
    GRBVar y = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "y");
    GRBVar z = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "z");

    // Set objective: maximize x + y + 2 z
    cout << x.get(GRB_StringAttr_VarName) << " " << endl;

    model.setObjective(x + y + 2 * z, GRB_MAXIMIZE);
    // Add constraint: x + 2 y + 3 z <= 4
    model.addConstr(x + 2 * y + 3 * z <= 4, "c0");
    // Add constraint: x + y >= 1
    model.addConstr(x + y >= 1, "c1");
    // Optimize model
    model.optimize();

    cout << x.get(GRB_StringAttr_VarName) << " "
        << x.get(GRB_DoubleAttr_X) << endl;
    cout << y.get(GRB_StringAttr_VarName) << " "

Solution

  • Gurobi has a lazy update approach. After you create your variables, you need to run model.update() to write the changes to your model. Only after that you can use the methods of a variable object:

    #include "gurobi_c++.h"
    using namespace std;
    
    int main(int argc, char *argv[]){
        GRBEnv env = GRBEnv();
    
        GRBModel model = GRBModel(env);
    
        // Create variables
    
        GRBVar x = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "x");
        GRBVar y = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "y");
        GRBVar z = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "z");
        model.update();
    
        // Set objective: maximize x + y + 2 z
        cout << x.get(GRB_StringAttr_VarName) << " " << endl;
    
        model.setObjective(x + y + 2 * z, GRB_MAXIMIZE);
        // Add constraint: x + 2 y + 3 z <= 4
        model.addConstr(x + 2 * y + 3 * z <= 4, "c0");
        // Add constraint: x + y >= 1
        model.addConstr(x + y >= 1, "c1");
        // Optimize model
        model.optimize();
    
        cout << x.get(GRB_StringAttr_VarName) << " " << x.get(GRB_DoubleAttr_X) << endl;
        cout << y.get(GRB_StringAttr_VarName) << " ";
    }
    

    Note that model.write() and model.optimize() both will call model.update() automatically. That's the reason why your second

     cout << x.get(GRB_StringAttr_VarName) << " " << x.get(GRB_DoubleAttr_X) << endl;
    

    works.