void addInitColumn(IloNumVarArray lambda, IloObjective rmpObj, IloRangeArray maintConEng, IloRangeArray removeMod, IloRangeArray convex, IloNumArray2 addXCol, IloNumArray addZCol, const IloNumArray compCosts, const IloNumArray convexityCoef) { // loop counter IloInt t; // counter for objective function coefficient for lambda // variable to be added. IloNum lambdaObjCoef = 0; // function assumes addXCol and addZCol contains proper values. // calculate objective function coefficient lambdaObjCoef for (t = 0; t < TIME_SPAN; t++) { // for each fixed t: scalar product of x[m]* vector and // component costs vector compCosts[m]: lambdaObjCoef += IloScalProd(addXCol[t],compCosts); // also clear the addXCol subarrays as soon as they // have been used addXCol[t].clear(); } // now add this column and it's associated lambda variable to the RMP. lambda.add(IloNumVar(rmpObj(lambdaObjCoef) + maintConEng(addZCol) + removeMod(addZCol) + convex(convexityCoef), 0.0, 1.0)); // clear addZCol num array. addZCol.clear(); } // END of addColumn
void addColumn(IloCplex subSolver, IloNumVarArray2 x, IloNumVarArray z, IloNumVarArray lambda, IloObjective rmpObj, IloRangeArray maintConEng, IloRangeArray removeMod, IloRangeArray convex, IloNumArray2 addXCol, IloNumArray addZCol, const IloNumArray compCosts, const IloNumArray convexityCoef) { // loop counter IloInt t; // counter for objective function coefficient for lambda // variable to be added. IloNum lambdaObjCoef = 0; // extract subproblem-optimal solution values // (into IloNumArrays addXCol (2d) and addZCol (1d)). // z values: subSolver.getValues(addZCol,z); //cout << endl << endl << "z = " << endl << addZCol << endl; //cin.get(); // !!! OBS !!! // here we might want to save these z values some column pool's custom-nitted class // array. Or to be specific, we want to add the indexes for NON-ZERO-ENTRIES in addZCol // to our class that keep place of columns. // E.g., given variable lambda(m)_(q_m), we want to know in our own class object, // given (m)(q_m), the indexes of non-zeros in that Z column. // and for each t... for (t = 0; t < TIME_SPAN; t++) { // x values: subSolver.getValues(addXCol[t],x[t]); //cout << endl << endl << "x[t=" << t << "] =" << endl << addXCol[t] << endl; } //cin.get(); // calculate objective function coefficient lambdaObjCoef for (t = 0; t < TIME_SPAN; t++) { // for each fixed t: scalar product of x[m]* vector and // component costs vector compCosts[m]: lambdaObjCoef += IloScalProd(addXCol[t],compCosts); // also clear the addXCol subarrays as soon as they // have been used addXCol[t].clear(); } // now add this column and it's associated lambda variable to the RMP. lambda.add(IloNumVar(rmpObj(lambdaObjCoef) + maintConEng(addZCol) + removeMod(addZCol) + convex(convexityCoef), 0.0, 1.0)); // clear addZCol num array. addZCol.clear(); } // END of addColumn
// This routine creates the master ILP (arc variables x and degree constraints). // // Modeling variables: // forall (i,j) in A: // x(i,j) = 1, if arc (i,j) is selected // = 0, otherwise // // Objective: // minimize sum((i,j) in A) c(i,j) * x(i,j) // // Degree constraints: // forall i in V: sum((i,j) in delta+(i)) x(i,j) = 1 // forall i in V: sum((j,i) in delta-(i)) x(j,i) = 1 // // Binary constraints on arc variables: // forall (i,j) in A: x(i,j) in {0, 1} // void createMasterILP(IloModel mod, Arcs x, IloNumArray2 arcCost) { IloInt i, j; IloEnv env = mod.getEnv(); IloInt numNodes = x.getSize(); // Create variables x(i,j) for (i,j) in A // For simplicity, also dummy variables x(i,i) are created. // Those variables are fixed to 0 and do not partecipate to // the constraints. char varName[100]; for (i = 0; i < numNodes; ++i) { x[i] = IloIntVarArray(env, numNodes, 0, 1); x[i][i].setBounds(0, 0); for (j = 0; j < numNodes; ++j) { sprintf(varName, "x.%d.%d", (int) i, (int) j); x[i][j].setName(varName); } mod.add(x[i]); } // Create objective function: minimize sum((i,j) in A ) c(i,j) * x(i,j) IloExpr obj(env); for (i = 0; i < numNodes; ++i) { arcCost[i][i] = 0; obj += IloScalProd(x[i], arcCost[i]); } mod.add(IloMinimize(env, obj)); obj.end(); // Add the out degree constraints. // forall i in V: sum((i,j) in delta+(i)) x(i,j) = 1 for (i = 0; i < numNodes; ++i) { IloExpr expr(env); for (j = 0; j < i; ++j) expr += x[i][j]; for (j = i+1; j < numNodes; ++j) expr += x[i][j]; mod.add(expr == 1); expr.end(); } // Add the in degree constraints. // forall i in V: sum((j,i) in delta-(i)) x(j,i) = 1 for (i = 0; i < numNodes; i++) { IloExpr expr(env); for (j = 0; j < i; j++) expr += x[j][i]; for (j = i+1; j < numNodes; j++) expr += x[j][i]; mod.add(expr == 1); expr.end(); } }// END createMasterILP
void kMST_ILP::addObjectiveFunction() { // multiply variable by cost IloIntArray edgeCost(env, instance.n_edges * 2); for (unsigned int i=0; i<edges.getSize(); i++) { edgeCost[i] = instance.edges[i % instance.n_edges].weight; } model.add(IloMinimize(env, IloScalProd(edges, edgeCost) )); }
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; }
int main(int argc, char **argv) { IloEnv env; try { IloInt i, j; IloNum rollWidth; IloNumArray amount(env); IloNumArray size(env); if ( argc > 1 ) readData(argv[1], rollWidth, size, amount); else readData("../../../examples/data/cutstock.dat", rollWidth, size, amount); /// CUTTING-OPTIMIZATION PROBLEM /// IloModel cutOpt (env); IloObjective RollsUsed = IloAdd(cutOpt, IloMinimize(env)); IloRangeArray Fill = IloAdd(cutOpt, IloRangeArray(env, amount, IloInfinity)); IloNumVarArray Cut(env); IloInt nWdth = size.getSize(); for (j = 0; j < nWdth; j++) { Cut.add(IloNumVar(RollsUsed(1) + Fill[j](int(rollWidth / size[j])))); } IloCplex cutSolver(cutOpt); /// PATTERN-GENERATION PROBLEM /// IloModel patGen (env); IloObjective ReducedCost = IloAdd(patGen, IloMinimize(env, 1)); IloNumVarArray Use(env, nWdth, 0.0, IloInfinity, ILOINT); patGen.add(IloScalProd(size, Use) <= rollWidth); IloCplex patSolver(patGen); /// COLUMN-GENERATION PROCEDURE /// IloNumArray price(env, nWdth); IloNumArray newPatt(env, nWdth); /// COLUMN-GENERATION PROCEDURE /// for (;;) { /// OPTIMIZE OVER CURRENT PATTERNS /// cutSolver.solve(); report1 (cutSolver, Cut, Fill); /// FIND AND ADD A NEW PATTERN /// for (i = 0; i < nWdth; i++) { price[i] = -cutSolver.getDual(Fill[i]); } ReducedCost.setLinearCoefs(Use, price); patSolver.solve(); report2 (patSolver, Use, ReducedCost); if (patSolver.getValue(ReducedCost) > -RC_EPS) break; patSolver.getValues(newPatt, Use); Cut.add( IloNumVar(RollsUsed(1) + Fill(newPatt)) ); } cutOpt.add(IloConversion(env, Cut, ILOINT)); cutSolver.solve(); cout << "Solution status: " << cutSolver.getStatus() << endl; report3 (cutSolver, Cut); } catch (IloException& ex) { cerr << "Error: " << ex << endl; } catch (...) { cerr << "Error" << endl; } env.end(); return 0; }
int main(int, char**) { IloEnv env; try { IloInt j; define_data(env); IloModel model(env); IloNumVarArray m(env, nbElements, 0.0, IloInfinity); IloNumVarArray r(env, nbRaw, 0.0, IloInfinity); IloNumVarArray s(env, nbScrap, 0.0, IloInfinity); IloNumVarArray i(env, nbIngot, 0, 100000, ILOINT); IloNumVarArray e(env, nbElements); // Objective Function: Minimize Cost model.add(IloMinimize(env, IloScalProd(nm, m) + IloScalProd(nr, r) + IloScalProd(ns, s) + IloScalProd(ni, i) )); // Min and max quantity of each element in alloy for (j = 0; j < nbElements; j++) e[j] = IloNumVar(env, p[j] * alloy, P[j] * alloy); // Constraint: produce requested quantity of alloy model.add(IloSum(e) == alloy); // Constraints: Satisfy element quantity requirements for alloy for (j = 0; j < nbElements; j++) { model.add(e[j] == m[j] + IloScalProd(PRaw[j], r) + IloScalProd(PScrap[j], s) + IloScalProd(PIngot[j], i)); } // Optimize IloCplex cplex(model); cplex.setOut(env.getNullStream()); cplex.setWarning(env.getNullStream()); cplex.solve(); if (cplex.getStatus() == IloAlgorithm::Infeasible) env.out() << "No Solution" << endl; env.out() << "Solution status: " << cplex.getStatus() << endl; // Print results env.out() << "Cost:" << cplex.getObjValue() << endl; env.out() << "Pure metal:" << endl; for(j = 0; j < nbElements; j++) env.out() << j << ") " << cplex.getValue(m[j]) << endl; env.out() << "Raw material:" << endl; for(j = 0; j < nbRaw; j++) env.out() << j << ") " << cplex.getValue(r[j]) << endl; env.out() << "Scrap:" << endl; for(j = 0; j < nbScrap; j++) env.out() << j << ") " << cplex.getValue(s[j]) << endl; env.out() << "Ingots : " << endl; for(j = 0; j < nbIngot; j++) env.out() << j << ") " << cplex.getValue(i[j]) << endl; env.out() << "Elements:" << endl; for(j = 0; j < nbElements; j++) env.out() << j << ") " << cplex.getValue(e[j]) << endl; } catch (IloException& ex) { cerr << "Error: " << ex << endl; } catch (...) { cerr << "Error" << endl; } env.end(); return 0; }
ILOSTLBEGIN int main(int, char**) { IloEnv env; try { IloInt nbMachines = 6; IloNumArray cost (env, nbMachines, 15.0, 20.0, 45.0, 64.0, 12.0, 56.0); IloNumArray capacity (env, nbMachines, 100.0, 20.0, 405.0, 264.0, 12.0, 256.0); IloNumArray fixedCost(env, nbMachines, 1900.0, 820.0, 805.0, 464.0, 3912.00, 556.0); IloNum demand = 22.0; IloModel model(env); IloNumVarArray x(env, nbMachines, 0, IloInfinity); IloNumVarArray fused(env, nbMachines, 0, 1, ILOINT); // Objective: minimize the sum of fixed and variable costs model.add(IloMinimize(env, IloScalProd(cost, x) + IloScalProd(fused, fixedCost))); IloInt i; for(i = 0; i < nbMachines; i++) { // Constraint: respect capacity constraint on machine 'i' model.add(x[i] <= capacity[i]); // Constraint: only produce product on machine 'i' if it is 'used' // (to capture fixed cost of using machine 'i') model.add(x[i] <= capacity[i]*fused[i]); } // Constraint: meet demand model.add(IloSum(x) == demand); IloCplex cplex(env); cplex.extract(model); cplex.solve(); cout << "Solution status: " << cplex.getStatus() << endl; cout << "Obj " << cplex.getObjValue() << endl; IloNum eps = cplex.getParam( IloCplex::Param::MIP::Tolerances::Integrality); for(i = 0; i < nbMachines; i++) { if (cplex.getValue(fused[i]) > eps) { cout << "E" << i << " is used for "; cout << cplex.getValue(x[i]) << endl; } } cout << endl; cout << "----------------------------------------" << endl; } catch (IloException& ex) { cerr << "Error: " << ex << endl; } env.end(); return 0; }
int main() { IloEnv env; try { NumMatrix cost(env, nbMonths); cost[0]=IloNumArray(env, nbProducts, 110.0, 120.0, 130.0, 110.0, 115.0); cost[1]=IloNumArray(env, nbProducts, 130.0, 130.0, 110.0, 90.0, 115.0); cost[2]=IloNumArray(env, nbProducts, 110.0, 140.0, 130.0, 100.0, 95.0); cost[3]=IloNumArray(env, nbProducts, 120.0, 110.0, 120.0, 120.0, 125.0); cost[4]=IloNumArray(env, nbProducts, 100.0, 120.0, 150.0, 110.0, 105.0); cost[5]=IloNumArray(env, nbProducts, 90.0, 100.0, 140.0, 80.0, 135.0); // Variable definitions IloNumVarArray produce(env, nbMonths, 0, IloInfinity); NumVarMatrix use(env, nbMonths); NumVarMatrix buy(env, nbMonths); NumVarMatrix store(env, nbMonths); IloInt i, p; for (i = 0; i < nbMonths; i++) { use[i] = IloNumVarArray(env, nbProducts, 0, IloInfinity); buy[i] = IloNumVarArray(env, nbProducts, 0, IloInfinity); store[i] = IloNumVarArray(env, nbProducts, 0, 1000); } IloExpr profit(env); IloModel model(env); // For each type of raw oil we must have 500 tons at the end for (p = 0; p < nbProducts; p++) { store[nbMonths-1][p].setBounds(500, 500); } // Constraints on each month for (i = 0; i < nbMonths; i++) { // Not more than 200 tons of vegetable oil can be refined model.add(use[i][v1] + use[i][v2] <= 200); // Not more than 250 tons of non-vegetable oil can be refined model.add(use[i][o1] + use[i][o2] + use[i][o3] <= 250); // Constraints on food composition model.add(3 * produce[i] <= 8.8 * use[i][v1] + 6.1 * use[i][v2] + 2 * use[i][o1] + 4.2 * use[i][o2] + 5 * use[i][o3]); model.add(8.8 * use[i][v1] + 6.1 * use[i][v2] + 2 * use[i][o1] + 4.2 * use[i][o2] + 5 * use[i][o3] <= 6 * produce[i]); model.add(produce[i] == IloSum(use[i])); // Raw oil can be stored for later use if (i == 0) { for (IloInt p = 0; p < nbProducts; p++) model.add(500 + buy[i][p] == use[i][p] + store[i][p]); } else { for (IloInt p = 0; p < nbProducts; p++) model.add(store[i-1][p] + buy[i][p] == use[i][p] + store[i][p]); } // Logical constraints // The food cannot use more than 3 oils // (or at least two oils must not be used) model.add((use[i][v1] == 0) + (use[i][v2] == 0) + (use[i][o1] == 0) + (use[i][o2] == 0) + (use[i][o3] == 0) >= 2); // When an oil is used, the quantity must be at least 20 tons for (p = 0; p < nbProducts; p++) model.add((use[i][p] == 0) || (use[i][p] >= 20)); // If products v1 or v2 are used, then product o3 is also used model.add(IloIfThen(env, (use[i][v1] >= 20) || (use[i][v2] >= 20), use[i][o3] >= 20)); // Objective function profit += 150 * produce[i] - IloScalProd(cost[i], buy[i]) - 5 * IloSum(store[i]); } // Objective function model.add(IloMaximize(env, profit)); IloCplex cplex(model); if (cplex.solve()) { cout << "Solution status: " << cplex.getStatus() << endl; cout << " Maximum profit = " << cplex.getObjValue() << endl; for (IloInt i = 0; i < nbMonths; i++) { IloInt p; cout << " Month " << i << " " << endl; cout << " . buy "; for (p = 0; p < nbProducts; p++) { cout << cplex.getValue(buy[i][p]) << "\t "; } cout << endl; cout << " . use "; for (p = 0; p < nbProducts; p++) { cout << cplex.getValue(use[i][p]) << "\t "; } cout << endl; cout << " . store "; for (p = 0; p < nbProducts; p++) { cout << cplex.getValue(store[i][p]) << "\t "; } cout << endl; } } else { cout << " No solution found" << endl; } } catch (IloException& ex) { cerr << "Error: " << ex << endl; } catch (...) { cerr << "Error" << endl; } env.end(); return 0; }
ILOSTLBEGIN int main(int argc, char** argv) { IloEnv env ; try { IloModel model(env) ; IloCplex cplex(env) ; // Get data // Import data from file try { //IloInt i, j ; const char* filename ; if (argc > 1) filename = argv[1] ; else filename = "data/tsp.dat" ; ifstream f(filename, ios::in) ; if (!f) { cerr << "No such file: " << filename << endl ; throw(1) ; } // Create data matrix IloArray<IloNumArray> costmatrix (env) ; f >> costmatrix ; IloInt n = costmatrix.getSize() ; // Define variables and "fill" them so as not to get seg faults IloArray<IloIntVarArray> x (env, n) ; for (i=0 ; i<n ; i++) { x[i] = IloIntVarArray (env, n) ; for(IloInt j=0 ; j<n ; j++) { x[i][j] = IloIntVar (env) ; } } IloIntVarArray u (env, n) ; for(i=0 ; i<n ; i++) { u[i] = IloIntVar (env) ; } // Define constraints IloExpr constr_i (env) ; IloExpr constr_j (env) ; IloExpr constr_u (env) ; // Vertical constraint // Create a full vector with a hole to express the vertical constraint as a scalar product IloIntArray basevector (env, n) ; basevector[0] = 0 ; for (int i=1 ; i<n ; i++) { basevector[i] = 1 ; } constr_i = IloScalProd(basevector, x[0]) ; model.add( constr_i == 1) ; for (i=1 ; i < n ; i++) { basevector[i-1] = 1 ; basevector[i] = 0 ; constr_i = IloScalProd(basevector, x[i]) ; model.add(constr_i == 1) ; for (j=0 ; j < n ; j++) { if (i != j) { constr_j += x[j][i] ; constr_u = u[i] - u[j] + n*x[i][j] ; model.add(constr_u == 1) ; } } model.add(constr_j == 1) ; } // Define objective IloExpr obj (env) ; for (i=1 ; i < n ; i++) { for (j=0 ; j < n ; j++) { if (i != j) { obj += costmatrix[i][j] * x[i][j] ; } } } model.add( IloMinimize(env, obj) ) ; // Extract model cplex.extract(model); // Export model // Set parameters // Solve if ( !cplex.solve() ) { env.error() << "Failed to optimize problem" << endl; cplex.out() << "Solution status " << cplex.getStatus() << endl ; cplex.out() << "Model" << cplex.getModel() << endl ; throw(-1); } cplex.out() << "Solution status " << cplex.getStatus() << endl; cplex.out() << "Objective value " << cplex.getObjValue() << endl; // Print solution details } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; } } catch (...) { cerr << "Unknown exception caught" << endl ; } // freeing memory env.end(); return 0; } // END main
int main(int argc, const char* argv[]){ IloEnv env; try{ IloModel model(env); IloInt i, j; const char* filename = "../../../examples/data/facility.data"; if (argc > 1) filename = argv[1]; std::ifstream file(filename); if (!file){ env.out() << "usage: " << argv[0] << " <file>" << std::endl; throw FileError(); } IloIntArray capacity(env), fixedCost(env); IloArray<IloIntArray> cost(env); IloInt nbLocations; IloInt nbStores; file >> nbLocations; file >> nbStores; capacity = IloIntArray(env, nbLocations); for(i = 0; i < nbLocations; i++){ file >> capacity[i]; } fixedCost = IloIntArray(env, nbLocations); for(i = 0; i < nbLocations; i++){ file >> fixedCost[i]; } for(j = 0; j < nbStores; j++){ cost.add(IloIntArray(env, nbLocations)); for(i = 0; i < nbLocations; i++){ file >> cost[j][i]; } } IloBool consistentData = (fixedCost.getSize() == nbLocations); consistentData = consistentData && nbStores <= IloSum(capacity); for (i = 0; consistentData && (i < nbStores); i++) consistentData = (cost[i].getSize() == nbLocations); if (!consistentData){ env.out() << "ERROR: data file '" << filename << "' contains inconsistent data" << std::endl; } IloIntVarArray supplier(env, nbStores, 0, nbLocations - 1); for (j = 0; j < nbLocations; j++) model.add(IloCount(supplier, j) <= capacity[j]); model.add(supplier[2] != supplier[7]); IloIntVarArray open(env, nbLocations, 0, 1); for (i = 0; i < nbStores; i++) model.add(open[supplier[i]] == 1); IloIntExpr obj = IloScalProd(open, fixedCost); for (i = 0; i < nbStores; i++) obj += cost[i][supplier[i]]; model.add(IloMinimize(env, obj)); IloCP cp(model); cp.setParameter(IloCP::LogVerbosity, IloCP::Quiet); cp.solve(); cp.out() << std::endl << "Optimal value: " << cp.getValue(obj) << std::endl; for (j = 0; j < nbLocations; j++){ if (cp.getValue(open[j]) == 1){ cp.out() << "Facility " << j << " is open, it serves stores "; for (i = 0; i < nbStores; i++){ if (cp.getValue(supplier[i]) == j) cp.out() << i << " "; } cp.out() << std::endl; } } } catch(IloException& e){ env.out() << " ERROR: " << e.getMessage() << std::endl; } env.end(); return 0; }
int main(int argc, char **argv) { IloEnv env; try { IloInt i, j; IloNumArray capacity(env), fixedCost(env); FloatMatrix cost(env); IloInt nbLocations; IloInt nbClients; const char* filename = "../../../examples/data/facility.dat"; if (argc > 1) filename = argv[1]; ifstream file(filename); if (!file) { cerr << "ERROR: could not open file '" << filename << "' for reading" << endl; cerr << "usage: " << argv[0] << " <file>" << endl; throw(-1); } file >> capacity >> fixedCost >> cost; nbLocations = capacity.getSize(); nbClients = cost.getSize(); IloBool consistentData = (fixedCost.getSize() == nbLocations); for(i = 0; consistentData && (i < nbClients); i++) consistentData = (cost[i].getSize() == nbLocations); if (!consistentData) { cerr << "ERROR: data file '" << filename << "' contains inconsistent data" << endl; throw(-1); } IloNumVarArray open(env, nbLocations, 0, 1, ILOINT); NumVarMatrix supply(env, nbClients); for(i = 0; i < nbClients; i++) supply[i] = IloNumVarArray(env, nbLocations, 0, 1, ILOINT); IloModel model(env); for(i = 0; i < nbClients; i++) model.add(IloSum(supply[i]) == 1); for(j = 0; j < nbLocations; j++) { IloExpr v(env); for(i = 0; i < nbClients; i++) v += supply[i][j]; model.add(v <= capacity[j] * open[j]); v.end(); } IloExpr obj = IloScalProd(fixedCost, open); for(i = 0; i < nbClients; i++) { obj += IloScalProd(cost[i], supply[i]); } model.add(IloMinimize(env, obj)); obj.end(); IloCplex cplex(env); cplex.extract(model); cplex.solve(); cplex.out() << "Solution status: " << cplex.getStatus() << endl; IloNum tolerance = cplex.getParam( IloCplex::Param::MIP::Tolerances::Integrality); cplex.out() << "Optimal value: " << cplex.getObjValue() << endl; for(j = 0; j < nbLocations; j++) { if (cplex.getValue(open[j]) >= 1 - tolerance) { cplex.out() << "Facility " << j << " is open, it serves clients "; for(i = 0; i < nbClients; i++) { if (cplex.getValue(supply[i][j]) >= 1 - tolerance) cplex.out() << i << " "; } cplex.out() << endl; } } } catch(IloException& e) { cerr << " ERROR: " << e << endl; } catch(...) { cerr << " ERROR" << endl; } env.end(); return 0; }
int main (void) { IloEnv env; try { IloModel model(env); IloCplex cplex(env); IloInt nbWhouses = 4; IloInt nbLoads = 31; IloInt w, l; IloNumVarArray capVars(env, nbWhouses, 0, 10, ILOINT); // Used capacities IloNumArray capLbs (env, nbWhouses, 2, 3, 5, 7); // Minimum usage level IloNumArray costs (env, nbWhouses, 1, 2, 4, 6); // Cost per warehouse // These variables represent the assigninment of a // load to a warehouse. IloNumVarArrayArray assignVars(env, nbWhouses); for (w = 0; w < nbWhouses; w++) { assignVars[w] = IloNumVarArray(env, nbLoads, 0, 1, ILOINT); // Links the number of loads assigned to a warehouse with // the capacity variable of the warehouse. model.add(IloSum(assignVars[w]) == capVars[w]); } // Each load must be assigned to just one warehouse. for (l = 0; l < nbLoads; l++) { IloNumVarArray aux(env); for (w = 0; w < nbWhouses; w++) aux.add(assignVars[w][l]); model.add(IloSum(aux) == 1); aux.end(); } model.add (IloMinimize(env, IloScalProd(costs, capVars))); cplex.extract(model); cplex.setParam(IloCplex::Param::MIP::Strategy::Search, IloCplex::Traditional); if ( cplex.solve(SemiContGoal(env, capVars, capLbs)) ) { cout << " --------------------------------------------------" << endl; cout << "Solution status: " << cplex.getStatus() << endl; cout << endl << "Solution found:" << endl; cout << " Objective value = " << cplex.getObjValue() << endl << endl; for (w = 0; w < nbWhouses; w++) { cout << "Warehouse " << w << ": stored " << cplex.getValue(capVars[w]) << " loads" << endl; for (l = 0; l < nbLoads; l++) { if ( cplex.getValue(assignVars[w][l]) > 1e-5 ) cout << "Load " << l << " | "; } cout << endl << endl; } cout << " --------------------------------------------------" << endl; } else { cout << " No solution found " << endl; } } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; } env.end(); return 0; } // END main