CPlexSolver::CPlexSolver(const Matrix& A, unsigned int lambda) : env(), model(env), vars(env), constraints(env), solutionVectors() { // Add variables for (int i = 0; i < A.shape()[1]; i++) { vars.add(IloBoolVar(env)); // For simple t-designs } // Add constraints for (int i = 0; i < A.shape()[0]; i++) { constraints.add(IloRange(env, lambda, lambda)); // RHS = lambda in every equation } // Set up model to have as few block orbits as possible IloObjective objective = IloMinimize(env); for (int i = 0; i < A.shape()[1]; i++) { objective.setLinearCoef(vars[i], 1); } // Set up constraints according to input matrix for (int i = 0; i < A.shape()[0]; i++) { for (int j = 0; j < A.shape()[1]; j++) { constraints[i].setLinearCoef(vars[j], A[i][j]); } } // TODO - names for constraints/vars may be necessary // Might have to name these after the row/col labels for K-M Matrix // Finish setting up the model model.add(objective); model.add(constraints); }
static void populatebycolumn (IloModel model, IloNumVarArray x, IloRangeArray c) { IloEnv env = model.getEnv(); IloObjective obj = IloMaximize(env); c.add(IloRange(env, -IloInfinity, 20.0)); c.add(IloRange(env, -IloInfinity, 30.0)); x.add(IloNumVar(obj(1.0) + c[0](-1.0) + c[1]( 1.0), 0.0, 40.0)); x.add(obj(2.0) + c[0]( 1.0) + c[1](-3.0)); x.add(obj(3.0) + c[0]( 1.0) + c[1]( 1.0)); model.add(obj); model.add(c); } // END populatebycolumn
static void populatebynonzero (IloModel model, IloIntVarArray x, IloRangeArray c) { IloEnv env = model.getEnv(); IloObjective obj = IloMaximize(env); int n, a; scanf("%d", &n); scanf("%d", &a); //restrição c.add(IloRange(env, -IloInfinity, a)); //variaveis for(int i=0 ; i<n; i++){ x.add(IloIntVar(env, 0, 1)); } /*x.add(IloIntVar(env, 0.0, 40.0)); x.add(IloIntVar(env)); x.add(IloIntVar(env));*/ /*obj.setLinearCoef(x[0], 1.0); obj.setLinearCoef(x[1], 2.0); obj.setLinearCoef(x[2], 3.0);*/ /*restricoes*/ for(int i=0 ; i<n; i++){ scanf("%d", &a); c[0].setLinearCoef(x[i], a); } //objetivo for(int i=0 ; i<n; i++){ scanf("%d", &a); obj.setLinearCoef(x[i], a); } /*c[0].setLinearCoef(x[1], 1.0); c[0].setLinearCoef(x[2], 1.0); c[1].setLinearCoef(x[0], 1.0); c[1].setLinearCoef(x[1], -3.0); c[1].setLinearCoef(x[2], 1.0);*/ c[0].setName("c1"); for(int i=0; i<n; i++){ char tmp[10]; printf("x%d", i+1); x[i].setName(tmp); } model.add(obj); model.add(c); } // END populatebynonzero
void CPLEXSolver::add_in_constraint(LinearConstraint *con, double coef){ DBG("Creating a Gurobi representation of a constriant %s\n", ""); IloNumArray weights(*env, (IloInt)con->_coefficients.size()); IloNumVarArray vars(*env, (IloInt)con->_variables.size()); for(unsigned int i = 0; i < con->_variables.size(); ++i){ DBG("\tAdding variable to CPLEX\n%s", ""); IloNumVar var_ptr; if(con->_variables[i]->_var == NULL){ IloNumVar::Type type; if(con->_variables[i]->_continuous) type = IloNumVar::Float; // else if(con->_lower == 0 && con->_upper == 1) type = IloNumVar::Bool; else type = IloNumVar::Int; var_ptr = IloNumVar(getEnv(), con->_variables[i]->_lower, // LB con->_variables[i]->_upper, // UB type); int *var_id = new int; *var_id = variables->getSize(); variables->add(var_ptr); con->_variables[i]->_var = (void*) var_id; DBG("Created new variable with id %d. type:%c lb:%f ub:%f coef:%f\n", *var_id, type, con->_variables[i]->_lower, con->_variables[i]->_upper, coef); } else { var_ptr = (*variables)[*(int*)(con->_variables[i]->_var)]; } vars[i] = (*variables)[*(int*)(con->_variables[i]->_var)]; weights[i] = con->_coefficients[i]; } IloNumExprArg lin_expr = IloScalProd(weights, vars); if(coef < -0.1){ model->add(IloMinimize(*env, lin_expr)); } else if(coef > 0.1){ model->add(IloMaximize(*env, lin_expr)); } else { if(con->_lhs > -INFINITY && con->_rhs < INFINITY){ if(con->_lhs == con->_rhs) { model->add(lin_expr == con->_lhs); } else { model->add(IloRange(*env, con->_lhs, lin_expr, con->_rhs)); } } else if(con->_lhs > -INFINITY) model->add(lin_expr >= con->_lhs); else if(con->_rhs < INFINITY) model->add(lin_expr <= con->_rhs); } }
int main() { IloEnv env; try { IloModel model(env); setData(env); IloNumVarArray inside(env, nbProds); IloNumVarArray outside(env, nbProds); IloObjective obj = IloAdd(model, IloMinimize(env)); // Must meet demand for each product for(IloInt p = 0; p < nbProds; p++) { IloRange demRange = IloAdd(model, IloRange (env, demand[p], demand[p])); inside[p] = IloNumVar(obj(insideCost[p]) + demRange(1)); outside[p] = IloNumVar(obj(outsideCost[p]) + demRange(1)); } // Must respect capacity constraint for each resource for(IloInt r = 0; r < nbResources; r++) model.add(IloScalProd(consumption[r], inside) <= capacity[r]); IloCplex cplex(env); cplex.extract(model); cplex.solve(); if (cplex.getStatus() != IloAlgorithm::Optimal) cout << "No optimal solution" << endl; cout << "Solution status: " << cplex.getStatus() << endl; displayResults(cplex, inside, outside); cout << "----------------------------------------" << endl; } catch (IloException& ex) { cerr << "Error: " << ex << endl; } catch (...) { cerr << "Error" << endl; } env.end(); return 0; }
void MILPSolverCPX::addRow(const vector<pair<int,double> > & entries, const double & lb, const double & ub) { static const bool debug = false; if (debug) cout << "Adding row to LP: "; IloRange & newRange = modelcon->data[rowCount] = IloAdd(*model, IloRange(*env, lb,ub)); map<int,double> & dest = coeffs[rowCount]; const int entCount = entries.size(); for (int i = 0; i < entCount; ++i) { newRange.setLinearCoef((*modelvar)[entries[i].first], entries[i].second); dest[entries[i].first] = entries[i].second; if (debug) { if (i) cout << " + "; cout << entries[i].second << "*" << entries[i].first; } } if (debug) { if (lb == -IloInfinity) { cout << " <= " << ub << "\n"; } else if (ub == IloInfinity) { cout << " >= " << lb << "\n"; } else if (ub == lb) { cout << " == " << ub << "\n"; } else { cout << " in [" << lb << "," << ub << "]\n"; } } ++rowCount; }
MILPSolverCPX::MILPSolverCPX(MILPSolverCPX & c) { static const bool debug = false; if (debug) { cout << "Copying...\n"; ostringstream copyfn; copyfn << "copyconstructor" << *(c.envUsers) << ".lp"; const string copyfns = copyfn.str(); c.writeLp(copyfns.c_str()); } env = c.env; envUsers = c.envUsers; ++(*envUsers); model = new IloModel(*env); modelvar = new IloNumVarArray(*env); modelcon = new Constraints(); obj = new IloObjective(*env); obj->setSense(IloObjective::Minimize); model->add(*obj); colCount = c.colCount; rowCount = c.rowCount; integervars = c.integervars; map<int,bool>::const_iterator iItr = integervars.begin(); const map<int,bool>::const_iterator iEnd = integervars.end(); for (int ci = 0; ci < colCount; ++ci) { const double lb = (*(c.modelvar))[ci].getLB(); const double ub = (*(c.modelvar))[ci].getUB(); if (iItr != iEnd && iItr->first == ci) { modelvar->add(IloNumVar(*env, lb, ub, (iItr->second ? ILOBOOL : ILOINT))); //cout << "Column " << ci << " in the copy is an integer\n"; ++iItr; } else { modelvar->add(IloNumVar(*env, lb, ub)); } const char * oldName = (*(c.modelvar))[ci].getName(); (*modelvar)[ci].setName(oldName); } coeffs = c.coeffs; map<int,map<int,double> >::const_iterator coItr = coeffs.begin(); const map<int,map<int,double> >::const_iterator coEnd = coeffs.end(); map<int,IloRange>::iterator dItr = c.modelcon->data.begin(); const map<int,IloRange>::iterator dEnd = c.modelcon->data.end(); for (int r = 0; dItr != dEnd; ++r, ++dItr) { const double lb = dItr->second.getLB(); const double ub = dItr->second.getUB(); IloRange & newRange = modelcon->data[r] = IloAdd(*model, IloRange(*env, lb,ub)); if (dItr->second.getName()) { newRange.setName(dItr->second.getName()); } if (coItr == coEnd) continue; if (r < coItr->first) continue; map<int,double>::const_iterator fItr = coItr->second.begin(); const map<int,double>::const_iterator fEnd = coItr->second.end(); for (; fItr != fEnd; ++fItr) { newRange.setLinearCoef((*modelvar)[fItr->first], fItr->second); } ++coItr; } cplex = new IloCplex(*model); setILS(cplex); solArray = 0; if (debug) { ostringstream copyfn; copyfn << "aftercopyconstructor" << *(c.envUsers) << ".lp"; const string copyfns = copyfn.str(); writeLp(copyfns.c_str()); } }
int main (int argc, char *argv[]) { ifstream infile; infile.open("Proj3_op.txt"); if(!infile){ cerr << "Unable to open the file\n"; exit(1); } cout << "Before Everything!!!" << "\n"; IloEnv env; IloInt i,j,varCount1,varCount2,varCount3,conCount; //same as “int i;” IloInt k,w,K,W,E,l,P,N,L; IloInt tab, newline, val; //from file char line[2048]; try { N = 9; K = 3; L = 36; W = (IloInt)atoi(argv[1]); IloModel model(env); //set up a model object IloNumVarArray var1(env);// C - primary cout << "Here\n"; IloNumVarArray var2(env);// B - backup cout << "here1\n"; IloNumVarArray var3(env);// = IloNumVarArray(env,W); //declare an array of variable objects, for unknowns IloNumVar W_max(env, 0, W, ILOINT); //var1: c_ijk_w IloRangeArray con(env);// = IloRangeArray(env,N*N + 3*w); //declare an array of constraint objects IloNumArray2 t = IloNumArray2(env,N); //Traffic Demand IloNumArray2 e = IloNumArray2(env,N); //edge matrix //IloObjective obj; //Define the Xijk matrix cout << "Before init xijkl\n"; Xijkl xijkl_m(env, L); for(l=0;l<L;l++){ xijkl_m[l] = Xijk(env, N); for(i=0;i<N;i++){ xijkl_m[l][i] = Xjk(env, N); for(j=0;j<N;j++){ xijkl_m[l][i][j] = IloNumArray(env, K); } } } //reset everything to zero here for(l=0;l<L;l++) for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) xijkl_m[l][i][j][k] = 0; input_Xijkl(xijkl_m); cout<<"bahre\n"; for(i=0;i<N;i++){ t[i] = IloNumArray(env,N); for(j=0;j<N;j++){ if(i == j) t[i][j] = IloNum(0); else if(i != j) t[i][j] = IloNum((i+j+2)%5); } } printf("ikde\n"); //Minimize W_max IloObjective obj=IloMinimize(env); obj.setLinearCoef(W_max, 1.0); cout << "here khali\n"; //Setting var1[] for Demands Constraints for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) for(w=0;w<W;w++) var1.add(IloNumVar(env, 0, 1, ILOINT)); //c_ijk_w variables set. //Setting var2[] for Demands Constraints for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) for(w=0;w<W;w++) var2.add(IloNumVar(env, 0, 1, ILOINT)); //b_ijk_w variables set. for(w = 0;w < W;w++) var3.add(IloNumVar(env, 0, 1, ILOINT)); //Variables for u_w cout<<"variables ready\n"; conCount = 0; for(i=0;i<N;i++) for(j=0;j<N;j++){ con.add(IloRange(env, 2 * t[i][j], 2 * t[i][j])); //varCount1 = 0; for(k=0;k<K;k++) for(w=0;w<W;w++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0); con[conCount].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w],1.0); } conCount++; }//Adding Demands Constraints to con cout<<"1st\n"; IloInt z= 0; for(w=0;w<W;w++){ for(l=0;l<L;l++){ con.add(IloRange(env, -IloInfinity, 1)); for(i=0;i<N;i++){ for(j=0;j<N;j++){ for(k=0;k<K;k++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],xijkl_m[l][i][j][k]); con[conCount].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w],xijkl_m[l][i][j][k]); } } } conCount++; } } cout<<"2nd\n"; //Adding Wavelength Constraints_1 to con P = N * (N-1) * K; for(w=0;w<W;w++){ con.add(IloRange(env, -IloInfinity, 0)); varCount1 = 0; for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0); con[conCount].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w],1.0); } con[conCount].setLinearCoef(var3[w],-P); conCount++; } cout<<"3rd\n"; for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) for(w=0;w<W;w++){ con.add(IloRange(env, -IloInfinity, 1)); con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w], 1.0); con[conCount++].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w], 1.0); } varCount3 = 0; for(w=0;w<W;w++){ con.add(IloRange(env, 0, IloInfinity)); con[conCount].setLinearCoef(W_max, 1.0); con[conCount++].setLinearCoef(var3[w], -1.0 * (w+1)); } cout<<"after constraints\n"; //model.add(obj); //add objective function into model model.add(IloMinimize(env,obj)); model.add(con); //add constraints into model IloCplex cplex(model); //create a cplex object and extract the //model to this cplex object // Optimize the problem and obtain solution. if ( !cplex.solve() ) { env.error() << "Failed to optimize LP" << endl; throw(-1); } IloNumArray vals(env); //declare an array to store the outputs //if 2 dimensional: IloNumArray2 vals(env); env.out() << "Solution status = " << cplex.getStatus() << endl; //return the status: Feasible/Optimal/Infeasible/Unbounded/Error/… env.out() << "Solution value = " << cplex.getObjValue() << endl; //return the optimal value for objective function cplex.getValues(vals, var1); //get the variable outputs env.out() << "Values Var1 = " << vals << endl; //env.out() : output stream cplex.getValues(vals, var3); env.out() << "Values Val3 = " << vals << endl; } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; } catch (...) { cerr << "Unknown exception caught" << endl; } env.end(); //close the CPLEX environment return 0; } // END main
int main(int argc) { IloEnv env; try { IloModel model(env); NumVarMatrix varOutput(env, J + current); NumVar3Matrix varHelp(env, J + current); Range3Matrix cons(env, J + current); for (int j = 0; j <J + current; j++){ varOutput[j] = IloNumVarArray(env, K); varHelp[j] = NumVarMatrix(env, K); cons[j] = RangeMatrix(env, K); for (int k = 0; k < K; k++){ varOutput[j][k] = IloNumVar(env, 0.0, IloInfinity); varHelp[j][k] = IloNumVarArray(env, L); cons[j][k] = IloRangeArray(env, C); for (int l = 0; l < L; l++){ varHelp[j][k][l] = IloNumVar(env, 0.0, IloInfinity); } if (j > current){ cons[j][k][0] = IloRange(env, 0.0, 0.0);//will be used to express equality of varOutput, constraint (0) cons[j][k][1] = IloRange(env, 0.0, IloInfinity);// constraint (1) cons[j][k][2] = IloRange(env, -IloInfinity, T[j] - Tdc - Tblow[j] - Tslack);// constraint (2) cons[j][k][3] = IloRange(env, Tfd[k], Tfd[k]);// constraint (3) cons[j][k][4] = IloRange(env, 0.0, IloInfinity);// constraint (4) cons[j][k][5] = IloRange(env, Tdf[k], IloInfinity);// constraint (5) cons[j][k][6] = IloRange(env, T[j - a[k]] + Tcd, T[j - a[k]] + Tcd);// constraint (6) cons[j][k][7] = IloRange(env, TlossD[k], IloInfinity);// constraint (7) cons[j][k][8] = IloRange(env, TlossF[k], IloInfinity);// constraint (8) } } } populatebynonzero(model, varOutput, varHelp, cons); IloCplex cplex(model); // Optimize the problem and obtain solution. if (!cplex.solve()) { env.error() << "Failed to optimize LP" << endl; throw(-1); } IloNumArray vals(env); IloNumVar val(env); //vars to save output double TimeAvailable[J][K]; double TimeInstances[J][K][L]; double LK103[J][2]; env.out() << "Solution status = " << cplex.getStatus() << endl; env.out() << "Solution value = " << cplex.getObjValue() << endl; for (int j = current; j < current + J; ++j) { cplex.getValues(vals, varOutput[j]); env.out() << "Seconds for load "<<j<<" = " << vals << endl; /*for (int k = 0; k < K; k++){ TimeAvailable[j][k] = cplex.getValue(varOutput[j][k]); }*/ } for (int j = current; j < current + J; j++){ for (int k = 0; k < K; k++){ cplex.getValues(vals, varHelp[j][k]); env.out() << "Time instances for spoon "<<k<<" in load "<<j<<" = " << vals << endl; /*for (int l = 0; l < L; l++){ TimeInstances[j][k][l] = cplex.getValue(varHelp[j][k][l]); }*/ } } for (int j = current + 2; j < J + current; j++){ LK103[j][0] = TimeInstances[j - 2][0][0]; LK103[j][1] = TimeInstances[j][0][5]; env.out() << "LK103, load " << j << " : " << LK103[j][1]-LK103[j][0] << endl; } /*cplex.getSlacks(vals, cons); env.out() << "Slacks = " << vals << endl; cplex.getDuals(vals, cons); env.out() << "Duals = " << vals << endl; cplex.getReducedCosts(vals, varOutput); env.out() << "Reduced Costs = " << vals << endl;*/ cplex.exportModel("lpex1.lp"); } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; } catch (...) { cerr << "Unknown exception caught" << endl; } env.end(); cin.get(); return 0; } // END main
void AssetAllocationModel::BuildCplexModel(IloEnv &env, IloModel &model, IloExpr &objective, unsigned int stage, const double *prev_decisions, const double *scenario, vector<IloNumVar> &decision_vars, vector<IloRange> &dual_constraints) const { //assets count N unsigned int assets = GetAssetsCount(); bool root_node = (stage == 1); bool last_stage = (stage == GetStagesCount()); double conf_inv = 1 - param_.confidence; double conf_inv_other = 1 - param_.confidence_other; IloNumVarArray x(env, assets); for (unsigned int i = 0; i < assets; ++i) { //zero lower bound x[i] = IloNumVar(env, 0.0); //max profit = min negative loss if (!root_node) { switch (param_.risk_measure) { case RISK_CVAR_NESTED: objective += -1 * x[i]; break; case RISK_CVAR_MULTIPERIOD: objective += -1 * param_.expectation_coefficients[stage - 1] * x[i]; break; } } decision_vars.push_back(x[i]); } model.add(x); //var c = positive value in the cvar IloNumVar c(env, 0.0); if (!root_node && (param_.risk_measure == RISK_CVAR_MULTIPERIOD)) { //objective with risk aversion coef lambda objective += param_.risk_coefficients[stage - 1] / conf_inv * c; model.add(c); } //var c_other = positive value in the cvar IloNumVar c_other(env, 0.0); if (!root_node && (param_.risk_measure == RISK_CVAR_MULTIPERIOD)) { //objective with risk aversion coef lambda objective += param_.risk_coefficients_other[stage - 1] / conf_inv_other * c_other; model.add(c_other); } //var var = variable to calculate CVaR = VaR level IloNumVar var(env, GetRecourseLowerBound(stage), GetRecourseUpperBound(stage)); //objective according to the risk aversion lambda if (!last_stage) { //last stage has no recourse objective += param_.risk_coefficients[stage] * var; } model.add(var); decision_vars.push_back(var); //var var_other = variable to calculate CVaR = VaR level IloNumVar var_other(env, GetRecourseLowerBound(stage), GetRecourseUpperBound(stage)); //objective according to the risk aversion lambda if (!last_stage) { //last stage has no recourse objective += param_.risk_coefficients_other[stage] * var_other; } model.add(var_other); decision_vars.push_back(var_other); //transaction costs dummy variable IloNumVarArray trans(env, assets); for (unsigned int i = 0; i < assets; ++i) { //zero lower bound trans[i] = IloNumVar(env, 0.0); } if (!root_node) { model.add(trans); } //constraint capital = sum of the weights equals initial capital one IloExpr cap_expr(env); double transaction_coef = param_.transaction_costs; for (unsigned int i = 0; i < assets; ++i) { cap_expr += x[i]; if (!root_node) { cap_expr += transaction_coef * trans[i]; } } double total_capital; if (root_node) { //no parent, init the capital with 1 total_capital = 1.0; } else { //sum up the capital under this scenario total_capital = CalculateCapital(prev_decisions, scenario); } IloRange capital(env, total_capital, cap_expr, total_capital); model.add(capital); dual_constraints.push_back(capital); //constraint transaction costs IloRangeArray costs_pos(env); IloRangeArray costs_neg(env); if (!root_node) { for (unsigned int i = 0; i < assets; ++i) { //current position in asset i double parent_value = scenario[i] * prev_decisions[i]; //decisions and scenarios have the same order here, decisions start with allocations //positive and negative part of linearization for absolute value IloExpr cost_expr_pos(env); IloExpr cost_expr_neg(env); cost_expr_pos += x[i]; cost_expr_pos += -1 * trans[i]; cost_expr_neg += -1 * x[i]; cost_expr_neg += -1 * trans[i]; costs_pos.add(IloRange(env, cost_expr_pos, parent_value)); costs_neg.add(IloRange(env, cost_expr_neg, -parent_value)); dual_constraints.push_back(costs_pos[i]); dual_constraints.push_back(costs_neg[i]); } model.add(costs_pos); model.add(costs_neg); } //contraint the positive part "c" of the CVaR value IloExpr cvar_expr(env); IloRange cvar; if (!root_node && (param_.risk_measure == RISK_CVAR_MULTIPERIOD)) { cvar_expr += c; //the varible itself for (unsigned int i = 0; i < assets; ++i) { cvar_expr += x[i]; //-c transp x } double parent_var = prev_decisions[assets]; //var is right after the allocations in decision vector cvar = IloRange(env, -parent_var, cvar_expr); //previous value at risk model.add(cvar); dual_constraints.push_back(cvar); } //contraint the positive part "c_other" of the CVaR value IloExpr cvar_expr_other(env); IloRange cvar_other; if (!root_node && (param_.risk_measure == RISK_CVAR_MULTIPERIOD)) { cvar_expr_other += c_other; //the varible itself for (unsigned int i = 0; i < assets; ++i) { cvar_expr_other += x[i]; //-c transp x } double parent_var_other = prev_decisions[assets + 1]; //var_other is right after var in the decisions vector cvar_other = IloRange(env, -parent_var_other, cvar_expr_other); //previous value at risk model.add(cvar_other); dual_constraints.push_back(cvar_other); } }
/** Create the dual of a linear program. * The function can only dualize programs of the form * <code>Ax <= b, x >= 0</code>. The data in <code>primalVars</code> and * <code>dualRows</code> as well as in <code>primalRows</code> and * <code>dualVars</code> is in 1-to-1-correspondence. * @param primalObj Objective function of primal problem. * @param primalVars Variables in primal problem. * @param primalRows Rows in primal problem. * @param dualObj Objective function of dual will be stored here. * @param dualVars All dual variables will be stored here. * @param dualRows All dual rows will be stored here. */ void BendersOpt::makeDual(IloObjective const &primalObj, IloNumVarArray const &primalVars, IloRangeArray const &primalRows, IloObjective *dualObj, IloNumVarArray *dualVars, IloRangeArray *dualRows) { // To keep the code simple we only support problems // of the form Ax <= b, b >= 0 here. We leave it as a reader's // exercise to extend the function to something that can handle // any kind of linear model. for (IloInt j = 0; j < primalVars.getSize(); ++j) if ( primalVars[j].getLB() != 0 || primalVars[j].getUB() < IloInfinity ) { std::stringstream s; s << "Cannot dualize variable " << primalVars[j]; throw s.str(); } for (IloInt i = 0; i < primalRows.getSize(); ++i) if ( primalRows[i].getLB() > -IloInfinity || primalRows[i].getUB() >= IloInfinity ) { std::stringstream s; s << "Cannot dualize constraint " << primalRows[i]; std::cerr << s.str() << std::endl; throw s.str(); } // The dual of // min/max c^T x // Ax <= b // x >= 0 // is // max/min y^T b // y^T A <= c // y <= 0 // We scale y by -1 to get >= 0 IloEnv env = primalVars.getEnv(); IloObjective obj(env, 0.0, primalObj.getSense() == IloObjective::Minimize ? IloObjective::Maximize : IloObjective::Minimize); IloRangeArray rows(env); IloNumVarArray y(env); std::map<IloNumVar,IloInt,ExtractableLess<IloNumVar> > v2i; for (IloInt j = 0; j < primalVars.getSize(); ++j) { IloNumVar x = primalVars[j]; v2i.insert(std::map<IloNumVar,IloInt,ExtractableLess<IloNumVar> >::value_type(x, j)); rows.add(IloRange(env, -IloInfinity, 0, x.getName())); } for (IloExpr::LinearIterator it = primalObj.getLinearIterator(); it.ok(); ++it) rows[v2i[it.getVar()]].setUB(it.getCoef()); for (IloInt i = 0; i < primalRows.getSize(); ++i) { IloRange r = primalRows[i]; IloNumColumn col(env); col += obj(-r.getUB()); for (IloExpr::LinearIterator it = r.getLinearIterator(); it.ok(); ++it) col += rows[v2i[it.getVar()]](-it.getCoef()); y.add(IloNumVar(col, 0, IloInfinity, IloNumVar::Float, r.getName())); } *dualObj = obj; *dualVars = y; *dualRows = rows; }
int main (int argc, char *argv[]) { ifstream infile; clock_t start_time, end_time; infile.open("Proj3_op.txt"); if(!infile){ cerr << "Unable to open the file\n"; exit(1); } cout << "Before Everything!!!" << "\n"; IloEnv env; IloInt i,j,varCount1,varCount2,varCount3,conCount; //same as “int i;” IloInt k,w,K,W,E,l,P,N,L; IloInt tab, newline, val; //from file char line[2048]; try { N = 9; K = 2; L = 36; W = (IloInt)atoi(argv[1]); IloModel model(env); //set up a model object IloNumVarArray var1(env);// = IloNumVarArray(env,K*W*N*N); IloNumVarArray var3(env);// = IloNumVarArray(env,W); //declare an array of variable objects, for unknowns IloNumVar W_max(env, 0, W, ILOINT); IloRangeArray con(env);// = IloRangeArray(env,N*N + 3*w); //declare an array of constraint objects IloNumArray2 t = IloNumArray2(env,N); //Traffic Demand IloNumArray2 e = IloNumArray2(env,N); //edge matrix //IloObjective obj; //Define the Xijk matrix Xijkl xijkl_m(env, L); for(l=0;l<L;l++){ xijkl_m[l] = Xijk(env, N); for(i=0;i<N;i++){ xijkl_m[l][i] = Xjk(env, N); for(j=0;j<N;j++){ xijkl_m[l][i][j] = IloNumArray(env, K); } } } //reset everything to zero here for(l=0;l<L;l++) for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) xijkl_m[l][i][j][k] = 0; input_Xijkl(xijkl_m); cout<<"bahre\n"; FILE *file; file = fopen(argv[2],"r"); int tj[10]; for(i=0;i<N;i++){ t[i] = IloNumArray(env,N); fscanf(file,"%d %d %d %d %d %d %d %d %d \n",&tj[0],&tj[1],&tj[2],&tj[3],&tj[4],&tj[5],&tj[6],&tj[7],&tj[8]); for(j=0;j<N;j++){ t[i][j] = IloNum(tj[j]); } } printf("ikde\n"); //Minimize W_max IloObjective obj=IloMinimize(env); obj.setLinearCoef(W_max, 1.0); cout << "here khali\n"; //Setting var1[] for Demands Constraints for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) for(w=0;w<W;w++) var1.add(IloNumVar(env, 0, 1, ILOINT)); for(w = 0;w < W;w++) var3.add(IloNumVar(env, 0, 1, ILOINT)); //Variables for u_w cout<<"variables ready\n"; conCount = 0; for(i=0;i<N;i++) for(j=0;j<N;j++){ con.add(IloRange(env, t[i][j], t[i][j])); //varCount1 = 0; for(k=0;k<K;k++) for(w=0;w<W;w++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0); //cout << "Before Adding Constraint\n"; //con[1].setLinearCoef(IloNumVar(env, 0, 1, ILOINT), 1.0); //cout<<"coef set "<<varCount1; } conCount++; }//Adding Demands Constraints to con cout<<"1st\n"; IloInt z= 0; for(w=0;w<W;w++){ for(l=0;l<L;l++){ con.add(IloRange(env, -IloInfinity, 1)); for(i=0;i<N;i++){ for(j=0;j<N;j++){ for(k=0;k<K;k++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],xijkl_m[l][i][j][k]); } } } conCount++; } } cout<<"2nd\n"; //Adding Wavelength Constraints_1 to con P = N * (N-1) * K; for(w=0;w<W;w++){ con.add(IloRange(env, -IloInfinity, 0)); varCount1 = 0; for(i=0;i<9;i++) for(j=0;j<9;j++) for(k=0;k<K;k++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0); } con[conCount].setLinearCoef(var3[w],-P); conCount++; } cout<<"3rd\n"; varCount3 = 0; for(w=0;w<W;w++){ con.add(IloRange(env, 0, IloInfinity)); con[conCount].setLinearCoef(W_max, 1.0); con[conCount++].setLinearCoef(var3[w], -1.0 * (w+1)); } cout<<"after constraints\n"; //model.add(obj); //add objective function into model model.add(IloMinimize(env,obj)); model.add(con); //add constraints into model IloCplex cplex(model); //create a cplex object and extract the //model to this cplex object // Optimize the problem and obtain solution. start_time = clock(); if ( !cplex.solve() ) { env.error() << "Failed to optimize LP" << endl; throw(-1); } end_time = clock(); IloNumArray vals(env); //declare an array to store the outputs IloNumVarArray opvars(env); //if 2 dimensional: IloNumArray2 vals(env); //env.out() << "Solution status = " << cplex.getStatus() << endl; //return the status: Feasible/Optimal/Infeasible/Unbounded/Error/… env.out() << "W_max value = " << cplex.getObjValue() << endl; //return the optimal value for objective function cplex.getValues(vals, var1); //get the variable outputs //env.out() << "Values Var1 = " << vals << endl; //env.out() : output stream cplex.getValues(vals, var3); //env.out() << "Values Val3 = " << vals << endl; } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; } catch (...) { cerr << "Unknown exception caught" << endl; } env.end(); //close the CPLEX environment float running_time (((float)end_time - (float)start_time)/CLOCKS_PER_SEC); cout << "*******RUNNING TIME: " << running_time << endl; return 0; } // END main
int main (int argc, char **argv) { int result = 0; IloEnv env; try { static int indices[] = { 0, 1, 2, 3, 4, 5, 6 }; IloModel model(env); /* ***************************************************************** * * * * S E T U P P R O B L E M * * * * The model we setup here is * * Minimize * * obj: 3x1 - x2 + 3x3 + 2x4 + x5 + 2x6 + 4x7 * * Subject To * * c1: x1 + x2 = 4 * * c2: x1 + x3 >= 3 * * c3: x6 + x7 <= 5 * * c4: -x1 + x7 >= -2 * * q1: [ -x1^2 + x2^2 ] <= 0 * * q2: [ 4.25x3^2 -2x3*x4 + 4.25x4^2 - 2x4*x5 + 4x5^2 ] + 2 x1 <= 9.0 * q3: [ x6^2 - x7^2 ] >= 4 * * Bounds * * 0 <= x1 <= 3 * * x2 Free * * 0 <= x3 <= 0.5 * * x4 Free * * x5 Free * * x7 Free * * End * * * * ***************************************************************** */ IloNumVarArray x(env); x.add(IloNumVar(env, 0, 3, "x1")); x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x2")); x.add(IloNumVar(env, 0, 0.5, "x3")); x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x4")); x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x5")); x.add(IloNumVar(env, 0, IloInfinity, "x6")); x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x7")); for (IloInt i = 0; i < x.getSize(); ++i) x[i].setObject(&indices[i]); IloObjective obj = IloMinimize(env, 3*x[0] - x[1] + 3*x[2] + 2*x[3] + x[4] + 2*x[5] + 4*x[6], "obj"); model.add(obj); IloRangeArray linear(env); linear.add(IloRange(env, 4.0, x[0] + x[1], 4.0, "c1")); linear.add(IloRange(env, 3.0, x[0] + x[2], IloInfinity, "c2")); linear.add(IloRange(env, -IloInfinity, x[5] + x[6], 5.0, "c3")); linear.add(IloRange(env, -2.0, -x[0] + x[6], IloInfinity, "c4")); for (IloInt i = 0; i < linear.getSize(); ++i) linear[i].setObject(&indices[i]); model.add(linear); IloRangeArray quad(env); quad.add(IloRange(env, -IloInfinity, -x[0]*x[0] + x[1] * x[1], 0, "q1")); quad.add(IloRange(env, -IloInfinity, 4.25*x[2]*x[2] - 2*x[2]*x[3] + 4.25*x[3]*x[3] + -2*x[3]*x[4] + 4*x[4]*x[4] + 2*x[0], 9.0, "q2")); quad.add(IloRange(env, 4.0, x[5]*x[5] - x[6]*x[6], IloInfinity, "q3")); for (IloInt i = 0; i < quad.getSize(); ++i) quad[i].setObject(&indices[i]); model.add(quad); /* ***************************************************************** * * * * O P T I M I Z E P R O B L E M * * * * ***************************************************************** */ IloCplex cplex(model); cplex.setParam(IloCplex::Param::Barrier::QCPConvergeTol, 1e-10); cplex.solve(); /* ***************************************************************** * * * * Q U E R Y S O L U T I O N * * * * ***************************************************************** */ IloNumArray xval(env); IloNumArray slack(env); IloNumArray qslack(env); IloNumArray cpi(env); IloNumArray rpi(env); IloNumArray qpi; cplex.getValues(x, xval); cplex.getSlacks(slack, linear); cplex.getSlacks(qslack, quad); cplex.getReducedCosts(cpi, x); cplex.getDuals(rpi, linear); qpi = getqconstrmultipliers(cplex, xval, quad); /* ***************************************************************** * * * * C H E C K K K T C O N D I T I O N S * * * * Here we verify that the optimal solution computed by CPLEX * * (and the qpi[] values computed above) satisfy the KKT * * conditions. * * * * ***************************************************************** */ // Primal feasibility: This example is about duals so we skip this test. // Dual feasibility: We must verify // - for <= constraints (linear or quadratic) the dual // multiplier is non-positive. // - for >= constraints (linear or quadratic) the dual // multiplier is non-negative. for (IloInt i = 0; i < linear.getSize(); ++i) { if ( linear[i].getLB() <= -IloInfinity ) { // <= constraint if ( rpi[i] > ZEROTOL ) { cerr << "Dual feasibility test failed for <= row " << i << ": " << rpi[i] << endl; result = -1; } } else if ( linear[i].getUB() >= IloInfinity ) { // >= constraint if ( rpi[i] < -ZEROTOL ) { cerr << "Dual feasibility test failed for >= row " << i << ":" << rpi[i] << endl; result = -1; } } else { // nothing to do for equality constraints } } for (IloInt q = 0; q < quad.getSize(); ++q) { if ( quad[q].getLB() <= -IloInfinity ) { // <= constraint if ( qpi[q] > ZEROTOL ) { cerr << "Dual feasibility test failed for <= quad " << q << ": " << qpi[q] << endl; result = -1; } } else if ( quad[q].getUB() >= IloInfinity ) { // >= constraint if ( qpi[q] < -ZEROTOL ) { cerr << "Dual feasibility test failed for >= quad " << q << ":" << qpi[q] << endl; result = -1; } } else { // nothing to do for equality constraints } } // Complementary slackness. // For any constraint the product of primal slack and dual multiplier // must be 0. for (IloInt i = 0; i < linear.getSize(); ++i) { if ( fabs (linear[i].getUB() - linear[i].getLB()) > ZEROTOL && fabs (slack[i] * rpi[i]) > ZEROTOL ) { cerr << "Complementary slackness test failed for row " << i << ": " << fabs (slack[i] * rpi[i]) << endl; result = -1; } } for (IloInt q = 0; q < quad.getSize(); ++q) { if ( fabs (quad[q].getUB() - quad[q].getLB()) > ZEROTOL && fabs (qslack[q] * qpi[q]) > ZEROTOL ) { cerr << "Complementary slackness test failed for quad " << q << ":" << fabs (qslack[q] * qpi[q]) << endl; result = -1; } } for (IloInt j = 0; j < x.getSize(); ++j) { if ( x[j].getUB() < IloInfinity ) { double const slk = x[j].getUB() - xval[j]; double const dual = cpi[j] < -ZEROTOL ? cpi[j] : 0.0; if ( fabs (slk * dual) > ZEROTOL ) { cerr << "Complementary slackness test failed for ub " << j << ": " << fabs (slk * dual) << endl; result = -1; } } if ( x[j].getLB() > -IloInfinity ) { double const slk = xval[j] - x[j].getLB(); double const dual = cpi[j] > ZEROTOL ? cpi[j] : 0.0; if ( fabs (slk * dual) > ZEROTOL ) { cerr << "Complementary slackness test failed for lb " << j << ": " << fabs (slk * dual) << endl; result = -1; } } } // Stationarity. // The difference between objective function and gradient at optimal // solution multiplied by dual multipliers must be 0, i.e., for the // optimal solution x // 0 == c // - sum(r in rows) r'(x)*rpi[r] // - sum(q in quads) q'(x)*qpi[q] // - sum(c in cols) b'(x)*cpi[c] // where r' and q' are the derivatives of a row or quadratic constraint, // x is the optimal solution and rpi[r] and qpi[q] are the dual // multipliers for row r and quadratic constraint q. // b' is the derivative of a bound constraint and cpi[c] the dual bound // multiplier for column c. IloNumArray kktsum(env, x.getSize()); // Objective function. for (IloExpr::LinearIterator it = obj.getLinearIterator(); it.ok(); ++it) kktsum[idx(it.getVar())] = it.getCoef(); // Linear constraints. // The derivative of a linear constraint ax - b (<)= 0 is just a. for (IloInt i = 0; i < linear.getSize(); ++i) { for (IloExpr::LinearIterator it = linear[i].getLinearIterator(); it.ok(); ++it) kktsum[idx(it.getVar())] -= rpi[i] * it.getCoef(); } // Quadratic constraints. // The derivative of a constraint xQx + ax - b <= 0 is // Qx + Q'x + a. for (IloInt q = 0; q < quad.getSize(); ++q) { for (IloExpr::LinearIterator it = quad[q].getLinearIterator(); it.ok(); ++it) kktsum[idx(it.getVar())] -= qpi[q] * it.getCoef(); for (IloExpr::QuadIterator it = quad[q].getQuadIterator(); it.ok(); ++it) { kktsum[idx(it.getVar1())] -= qpi[q] * xval[idx(it.getVar2())] * it.getCoef(); kktsum[idx(it.getVar2())] -= qpi[q] * xval[idx(it.getVar1())] * it.getCoef(); } } // Bounds. // The derivative for lower bounds is -1 and that for upper bounds // is 1. // CPLEX already returns dj with the appropriate sign so there is // no need to distinguish between different bound types here. for (IloInt j = 0; j < x.getSize(); ++j) kktsum[j] -= cpi[j]; for (IloInt j = 0; j < kktsum.getSize(); ++j) { if ( fabs (kktsum[j]) > ZEROTOL ) { cerr << "Stationarity test failed at index " << j << ": " << kktsum[j] << endl; result = -1; } } if ( result == 0) { // KKT conditions satisfied. Dump out the optimal solutions and // the dual values. streamsize oprec = cout.precision(3); ios_base::fmtflags oflags = cout.setf(ios::fixed | ios::showpos); cout << "Optimal solution satisfies KKT conditions." << endl; cout << " x[] = " << xval << endl; cout << " cpi[] = " << cpi << endl; cout << " rpi[] = " << rpi << endl; cout << " qpi[] = " << qpi << endl; cout.precision(oprec); cout.flags(oflags); } } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; result = -1; } catch (...) { cerr << "Unknown exception caught" << endl; result = -1; } env.end(); return result; } // END main