Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- This example formulates and solves the following simple QCP model:
- using the Gurobi API
- maximize 2x + 3y
- subject to x + y/2 + 3z = 5
- x^2 - y^2 <= z^2 (second-order cone)
- 2(x^2) <= yz (rotated second-order cone)
- */
- #define GU_NO_ERROR 0
- #define GU_ERR_GRP_EXCEPTION 2
- #define GU_ERR_EXCEPTION 3
- #include "gurobi_c++.h"
- using namespace std;
- int
- main(int argc,
- char *argv[])
- {
- try {
- GRBEnv* env = 0;
- GRPVar* x = 0;
- GRPVar* y = 0;
- GRPVar* z = 0;
- int sequenceState = 0;
- int retCode = GU_NO_ERROR;
- env = new GRBEnv(); // Create Environment
- GRBModel model = GRBModel(*env); // Make Model
- sequenceState = 1;
- model.set(GRB_StringAttr_ModelName, "QCP");
- x = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_CONTINUOUS, "x"); // Create variables as per the model
- sequenceState = 2;
- y = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_CONTINUOUS, "y");
- sequenceState = 3;
- z = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_CONTINUOUS, "z");
- sequenceState = 4;
- GRBLinExpr obj = (2*x) + y; // Set objective equation and maximize method
- model.setObjective(obj, GRB_MAXIMIZE);
- // x + y/2 + 3z = 5
- model.addConstr(x + (y/2.0) + (3.0*z) == 5.0, "c0"); // Add each constraint
- // x^2 - y^2 <= z^2
- model.addQConstr(x*x - y*y <= z*z, "qc0");
- // 2x^2 <= yz
- model.addQConstr((2.0*(x*x)) <= y*z, "qc1");
- // Optimize model
- model.optimize();
- cout << x.get(GRB_StringAttr_VarName) << " "
- << x.get(GRB_DoubleAttr_X) << endl;
- cout << y.get(GRB_StringAttr_VarName) << " "
- << y.get(GRB_DoubleAttr_X) << endl;
- cout << z.get(GRB_StringAttr_VarName) << " "
- << z.get(GRB_DoubleAttr_X) << endl;
- cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl;
- } catch(GRBException e) {
- cout << "Error code = " << e.getErrorCode() << endl;
- cout << e.getMessage() << endl;
- retCode = GU_ERR_GRP_EXCEPTION;
- } catch(...) {
- cout << "Exception during optimization" << endl;
- retCode = GU_ERR_EXCEPTION;
- }
- if (sequenceState >= 4) delete[] z;
- if (sequenceState >= 3) delete[] y;
- if (sequenceState >= 2) delete[] x;
- if (sequenceState >= 1) delete env;
- return retCode;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement