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); }
/* initialisiere N^2 Variablen und erstelle eine zu minimierende * Strecken-Zielfunktion über die Distanzmatrix c * * eigentlich sind nur (N*N-N)/2 Variablen nötig, aber dafür müsste * ich mir etwas schlaues zur Adressierung ausdenken (weil das untere linke * Dreieck einer Matrix adressiert werden muss, ist das nicht trivial) * Der Presolver scheint die überflüssigen Variablen allerdings * direkt zu verwerfen, weshalb das nicht dringend ist. * */ IloNumVarArray CplexTSPSolver::init_symmetric_var(IloModel model) { IloEnv env = model.getEnv(); // Edge Variables IloNumVarArray x(env); for(int i=0; i<N; i++) for(int j=0; j<N; j++) if(j<i) x.add(IloNumVar(env, 0, 1, mip ? ILOINT : ILOFLOAT)); else x.add(IloNumVar(env, 0, 0, ILOFLOAT)); // fülle oben rechts mit dummies model.add(x); // Cost Function IloExpr expr(env); // die folgenden Schleifen adressieren ein unteres linkes // Dreieck in einer quadratischen Matrix for(int i=0; i<N; i++) for (int j=0; j<i; j++) expr += c[i*N + j] * x[i*N + j]; model.add(IloMinimize(env, expr)); expr.end(); return x; }
ILOSTLBEGIN int main() { IloEnv env; try { IloModel model(env, "chvatal"); IloNumVarArray x(env, 12, 0.0, 50.0); model.add(IloMinimize(env, x[0] + x[1] + x[2] + x[3] + x[4] + x[5] + x[6] + 2*x[10] + 2*x[11] )); model.add( -x[7]-x[8]-x[9] == -1); model.add( x[0] +x[5] +x[7] == 4); model.add( x[1] +x[3] +x[6] +x[8] == 1); model.add( x[2] +x[4] +x[9] == 1); model.add( -x[5]-x[6] -x[10]+x[11] == -2); model.add( -x[3]-x[4] +x[10] == -2); model.add(-x[0]-x[1]-x[2] -x[11] == -1); IloCplex cplex(model); cplex.setParam(IloCplex::Param::Simplex::Display, 2); cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Network); cplex.solve(); cplex.out() << "After network optimization, objective is " << cplex.getObjValue() << endl; model.add(2*x[10] + 5*x[11] == 2); model.add( x[0] + x[2] + x[5] == 3); cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Dual); cplex.solve(); IloNumArray vals(env); cplex.getValues(vals, x); cplex.out() << "Solution status " << cplex.getStatus() << endl; cplex.out() << "Objective value " << cplex.getObjValue() << endl; cplex.out() << "Solution is: " << vals << endl; cplex.exportModel("lpex3.lp"); } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; } catch (...) { cerr << "Unknown exception caught" << endl; } env.end(); return 0; } // END main
void update() { switch (dir_) { case IP::MAX: model_.add(IloMaximize(env_, obj_)); break; case IP::MIN: model_.add(IloMinimize(env_, obj_)); break; } }
/** * Objective function: * $\sum_{i, j} c_{ij} x_{ij}$ */ static void addObjectiveFunction(IloEnv env, IloModel model, IloBoolVarArray xs, vector<Instance::Edge> edges, u_int n_edges) { IloExpr e_objective(env); for (u_int m = 0; m < n_edges; m++) { e_objective += xs[m] * edges[m].weight; } model.add(IloMinimize(env, e_objective)); e_objective.end(); }
// 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
int createObj(const Problem<double>& P,IloEnv& env, IloModel& model, IloNumVarMatrix& b){ IloExpr expr(env); for (int i=0;i<P.nbTask;++i) { for (int e=0;e<2*P.nbTask-1;++e) expr+=b[i][e]; } model.add(IloMinimize(env,expr)); expr.end(); return 0; }
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) )); }
int main(int, const char * []) { IloEnv env; try { IloInt i,j; IloModel model(env); IloNumExpr cost(env); IloIntervalVarArray allTasks(env); IloIntervalVarArray joeTasks(env); IloIntervalVarArray jimTasks(env); IloIntArray joeLocations(env); IloIntArray jimLocations(env); MakeHouse(model, cost, allTasks, joeTasks, jimTasks, joeLocations, jimLocations, 0, 0, 120, 100.0); MakeHouse(model, cost, allTasks, joeTasks, jimTasks, joeLocations, jimLocations, 1, 0, 212, 100.0); MakeHouse(model, cost, allTasks, joeTasks, jimTasks, joeLocations, jimLocations, 2, 151, 304, 100.0); MakeHouse(model, cost, allTasks, joeTasks, jimTasks, joeLocations, jimLocations, 3, 59, 181, 200.0); MakeHouse(model, cost, allTasks, joeTasks, jimTasks, joeLocations, jimLocations, 4, 243, 425, 100.0); IloTransitionDistance tt(env, 5); for (i=0; i<5; ++i) for (j=0; j<5; ++j) tt.setValue(i, j, IloAbs(i-j)); IloIntervalSequenceVar joe(env, joeTasks, joeLocations, "Joe"); IloIntervalSequenceVar jim(env, jimTasks, jimLocations, "Jim"); model.add(IloNoOverlap(env, joe, tt)); model.add(IloNoOverlap(env, jim, tt)); model.add(IloMinimize(env, cost)); /* EXTRACTING THE MODEL AND SOLVING. */ IloCP cp(model); if (cp.solve()) { cp.out() << "Solution with objective " << cp.getObjValue() << ":" << std::endl; for (i=0; i<allTasks.getSize(); ++i) { cp.out() << cp.domain(allTasks[i]) << std::endl; } } else { cp.out() << "No solution found. " << std::endl; } } catch (IloException& ex) { env.out() << "Error: " << ex << std::endl; } env.end(); return 0; }
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); } }
static void populatebyrow (IloModel model, IloNumVarArray x, IloRangeArray c) { IloEnv env = model.getEnv(); x.add(IloNumVar(env, -1.0, 1.0)); x.add(IloNumVar(env, 0.0, 1.0)); model.add(IloMinimize(env, 0.5 * (-3*x[0]*x[0] - 3*x[1]*x[1] + - 1*x[0]*x[1] ) )); c.add( - x[0] + x[1] >= 0); c.add( x[0] + x[1] >= 0); model.add(c); } // END populatebyrow
int main(int argc, const char *argv[]){ IloEnv env; try { IloModel model(env); IloInt nbTransmitters = GetTransmitterIndex(nbCell, 0); IloIntVarArray freq(env, nbTransmitters, 0, nbAvailFreq - 1); freq.setNames("freq"); for (IloInt cell = 0; cell < nbCell; cell++) for (IloInt channel1 = 0; channel1 < nbChannel[cell]; channel1++) for (IloInt channel2= channel1+1; channel2 < nbChannel[cell]; channel2++) model.add(IloAbs( freq[GetTransmitterIndex(cell, channel1)] - freq[GetTransmitterIndex(cell, channel2)] ) >= 16); for (IloInt cell1 = 0; cell1 < nbCell; cell1++) for (IloInt cell2 = cell1+1; cell2 < nbCell; cell2++) if (dist[cell1][cell2] > 0) for (IloInt channel1 = 0; channel1 < nbChannel[cell1]; channel1++) for (IloInt channel2 = 0; channel2 < nbChannel[cell2]; channel2++) model.add(IloAbs( freq[GetTransmitterIndex(cell1, channel1)] - freq[GetTransmitterIndex(cell2, channel2)] ) >= dist[cell1][cell2]); // Minimizing the total number of frequencies IloIntExpr nbFreq = IloCountDifferent(freq); model.add(IloMinimize(env, nbFreq)); IloCP cp(model); cp.setParameter(IloCP::CountDifferentInferenceLevel, IloCP::Extended); cp.setParameter(IloCP::FailLimit, 40000); cp.setParameter(IloCP::LogPeriod, 100000); if (cp.solve()) { for (IloInt cell = 0; cell < nbCell; cell++) { for (IloInt channel = 0; channel < nbChannel[cell]; channel++) cp.out() << cp.getValue(freq[GetTransmitterIndex(cell, channel)]) << " " ; cp.out() << std::endl; } cp.out() << "Total # of sites " << nbTransmitters << std::endl; cp.out() << "Total # of frequencies " << cp.getValue(nbFreq) << std::endl; } else cp.out() << "No solution found." << std::endl; cp.end(); } catch (IloException & ex) { env.out() << "Caught: " << ex << std::endl; } env.end(); return 0; }
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 CPLEX_LP_IMSTSolver_v2::generateGoal() { IloExpr goalFormula(env); IloInt i { }; IloInt varArraySize { }; EdgeIF* edge { }; INFO_NOARG(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_GOAL_CONSTRAINT); graph->beginEdge(); while (graph->hasNextEdge(Connectivity::CONNECTED, Visibility::VISIBLE)) { edge = graph->nextEdge(); INFO(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_GOAL_ADD, edge->getSourceVertex()->getVertexIdx(), edge->getTargetVertex()->getVertexIdx(), edge->getSourceVertex()->getVertexIdx(), edge->getTargetVertex()->getVertexIdx(), edge->getEdgeCost(), baseLPMSTSolution.at(edge->getSourceVertex()->getVertexIdx()).at( edge->getTargetVertex()->getVertexIdx()) ? '1' : '0'); goalFormula += edge->getEdgeCost() * baseLPMSTSolution.at( edge->getSourceVertex()->getVertexIdx()).at( edge->getTargetVertex()->getVertexIdx()); } INFO_NOARG(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_GOAL_INCR_CONSTRAINT); graph->beginEdge(); while (graph->hasNextEdge(Connectivity::CONNECTED, Visibility::VISIBLE)) { edge = graph->nextEdge(); INFO(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_GOAL_INCR_ADD, edge->getSourceVertex()->getVertexIdx(), edge->getTargetVertex()->getVertexIdx(), edge->getSourceVertex()->getVertexIdx(), edge->getTargetVertex()->getVertexIdx(), edge->getSourceVertex()->getVertexIdx(), edge->getTargetVertex()->getVertexIdx(), edge->getEdgeCost(), getVariableName(getAddEdgeVariable(edge)).c_str(), getVariableName(getDropEdgeVariable(edge)).c_str()); goalFormula += edge->getEdgeCost() * (getAddEdgeVariable(edge) - getDropEdgeVariable(edge)); } model.add(IloMinimize(env, goalFormula)); }
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 CProblem::setModel() { //time_t start, end; IloEnv env; try { IloModel model(env); IloCplex cplex(env); /*Variables*/ IloNumVar lambda(env, "lambda"); IloNumVarArray c(env, n); // for (unsigned int u = 0; u < n; u++) { std::stringstream ss; ss << u; std::string str = "c" + ss.str(); c[u] = IloNumVar(env, str.c_str()); } IloIntVarArray z0(env, Info.numAddVar); for (int i = 0; i < Info.numAddVar; i++) { std::stringstream ss; ss << i; std::string str = "z0_" + ss.str(); z0[i] = IloIntVar(env, 0, 1, str.c_str()); } /* Objective*/ model.add(IloMinimize(env, lambda)); /*Constrains*/ /* d=function of the distance */ IloArray<IloNumArray> Par_d(env, n); for (unsigned int u = 0; u < n; u++) { Par_d[u] = IloNumArray(env, n); for (unsigned int v = 0; v < n; v++) { Par_d[u][v] = d[u][v]; } } int M = (max_distance + 1) * n; for (int i = 0; i < Info.numAddVar; i++) { int u = Info.ConstrIndex[i * 2]; int v = Info.ConstrIndex[i * 2 + 1]; model.add(c[u] - c[v] + M * (z0[i]) >= Par_d[u][v]); model.add(c[v] - c[u] + M * (1 - z0[i]) >= Par_d[u][v]); } // d(x) = 3 - x if (max_distance == 2) { // Gridgraphen 1x2 (6 Knoten) for (int i = 0; i < sqrt(n)-1; i+=1) { for (int j = 0; j < sqrt(n)-2; j+=2) { model.add(c[i * sqrt(n) + j] + c[i * sqrt(n) + j+2] + c[(i+1) * sqrt(n) + j] + c[(i+1) * sqrt(n) + j+2] >= 16.2273); } } // } //d(x) = 4 - x if (max_distance == 3) { // Gridgraphen 1x2 (6 Knoten) for (int i = 0; i < sqrt(n)-1; i+=1) { for (int j = 0; j < sqrt(n)-2; j+=2) { model.add(c[i * sqrt(n) + j] + c[i * sqrt(n) + j+2] + c[(i+1) * sqrt(n) + j] + c[(i+1) * sqrt(n) + j+2] >= 30.283); } } } for (unsigned int v = 0; v < n; v++) { model.add(c[v] <= lambda); model.add(c[v] >= 0); } std::cout << "Number of variables " << Info.numVar << "\n"; /* solve the Model*/ cplex.extract(model); cplex.exportModel("L-Labeling.lp"); IloTimer timer(env); timer.start(); int solveError = cplex.solve(); timer.stop(); if (!solveError) { std::cout << "STATUS : " << cplex.getStatus() << "\n"; env.error() << "Failed to optimize LP \n"; exit(1); } //Info.time = (double)(end-start)/(double)CLOCKS_PER_SEC; Info.time = timer.getTime(); std::cout << "STATUS : " << cplex.getStatus() << "\n"; /* get the solution*/ env.out() << "Solution status = " << cplex.getStatus() << "\n"; Info.numConstr = cplex.getNrows(); env.out() << " Number of constraints = " << Info.numConstr << "\n"; lambda_G_d = cplex.getObjValue(); env.out() << "Solution value = " << lambda_G_d << "\n"; for (unsigned int u = 0; u < n; u++) { C.push_back(cplex.getValue(c[u])); std::cout << "c(" << u << ")=" << C[u] << " "; } } // end try catch (IloException& e) { std::cerr << "Concert exception caught: " << e << std::endl; } catch (...) { std::cerr << "Unknown exception caught" << std::endl; } env.end(); return 0; }
int main(int argc, const char* argv[]){ IloEnv env; try { const char* filename = "../../../examples/data/flowshop_default.data"; IloInt failLimit = IloIntMax; if (argc > 1) filename = argv[1]; if (argc > 2) failLimit = atoi(argv[2]); std::ifstream file(filename); if (!file){ env.out() << "usage: " << argv[0] << " <file> <failLimit>" << std::endl; throw FileError(); } IloInt i,j; IloModel model(env); IloInt nbJobs, nbMachines; file >> nbJobs; file >> nbMachines; IloIntervalVarArray2 machines(env, nbMachines); for (j = 0; j < nbMachines; j++) machines[j] = IloIntervalVarArray(env); IloIntExprArray ends(env); for (i = 0; i < nbJobs; i++) { IloIntervalVar prec; for (j = 0; j < nbMachines; j++) { IloInt d; file >> d; IloIntervalVar ti(env, d); machines[j].add(ti); if (0 != prec.getImpl()) model.add(IloEndBeforeStart(env, prec, ti)); prec = ti; } ends.add(IloEndOf(prec)); } IloIntervalSequenceVarArray seqs(env,nbMachines); for (j = 0; j < nbMachines; j++) { seqs[j] = IloIntervalSequenceVar(env, machines[j]); model.add(IloNoOverlap(env,seqs[j])); if (0<j) { model.add(IloSameSequence(env, seqs[0],seqs[j])); } } IloObjective objective = IloMinimize(env,IloMax(ends)); model.add(objective); IloCP cp(model); cp.setParameter(IloCP::FailLimit, failLimit); cp.setParameter(IloCP::LogPeriod, 10000); cp.out() << "Instance \t: " << filename << std::endl; if (cp.solve()) { cp.out() << "Makespan \t: " << cp.getObjValue() << std::endl; } else { cp.out() << "No solution found." << std::endl; } } catch(IloException& e){ env.out() << " ERROR: " << e << std::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; }
int CProblem::setModel() { //time_t start, end; numvar = 1+n; // lambda + all c; IloEnv env; try { IloModel model(env); IloCplex cplex(env); /*Variables*/ IloNumVar lambda(env, "lambda"); IloNumVarArray c(env, n);// for (unsigned int u=0; u<n; u++) { std::stringstream ss; ss << u; std::string str = "c" + ss.str(); c[u]=IloNumVar(env, str.c_str()); } IloArray<IloIntVarArray> z(env,n); for (unsigned int u=0; u<n; u++) { z[u]= IloIntVarArray(env, n); for (unsigned int v=0; v<n; v++) { std::stringstream ss; ss << u; ss << v; std::string str = "z" + ss.str(); z[u][v] = IloIntVar(env, 0, 1, str.c_str()); } } /* Constant M*/ int M=n*max_d; UB = M; /* Objective*/ model.add(IloMinimize(env, lambda)); /*Constrains*/ model.add(lambda - UB <= 0); /* d=function of the distance */ IloArray<IloNumArray> Par_d(env,n); for (unsigned int u=0; u<n; u++) { Par_d[u]=IloNumArray(env,n); for (unsigned int v=0; v<n; v++) { Par_d[u][v]=d[u][v]; } } for (unsigned u=0; u<n; u++) { for (unsigned v=0; v<u; v++) { model.add(c[v]-c[u]+M* z[u][v] >= Par_d[u][v] ); model.add(c[u]-c[v]+M*(1-z[u][v]) >= Par_d[u][v]); numvar++; // + z[u][v] } } for (unsigned int v=0; v<n; v++) { IloExpr expr; model.add (c[v] <= lambda); model.add (c[v] >= 0); expr.end(); } std::cout << "Number of variables " << numvar << "\n"; /* solve the Model*/ cplex.extract(model); cplex.exportModel("L-Labeling.lp"); /* start = clock(); int solveError = cplex.solve(); end = clock (); */ // cplex.setParam(IloCplex::Threads, 1); cplex.setParam(IloCplex::ClockType , 1 ); // CPU time IloTimer timer(env); const double startt = cplex.getTime(); timer.start(); int solveError = cplex.solve(); timer.stop(); const double stopt = cplex.getTime() - startt; if ( !solveError ) { std::cout << "STATUS : "<< cplex.getStatus() << "\n"; env.error() << "Failed to optimize LP \n"; exit(1); } //Info.time = (double)(end-start)/(double)CLOCKS_PER_SEC; Info.time = timer.getTime(); std::cout << "STATUS : "<< cplex.getStatus() << "\n"; /* get the solution*/ env.out() << "Solution status = " << cplex.getStatus() << "\n"; env.out() << "Time cplex.getTime " << stopt << "\n"; numconst = cplex.getNrows(); env.out() << " Number of constraints = " << numconst << "\n"; lambda_G_d=cplex.getObjValue(); env.out() << "Solution value = " << lambda_G_d << "\n"; for (unsigned int u=0; u<n; u++) { C.push_back(cplex.getValue(c[u])); std::cout << "c(" << u << ")=" << C[u]<< " "; } std::cout <<"\n"; /* for (unsigned int u=0; u<n; u++) { for (unsigned int v=0; v<u; v++) { std::cout<< "z[" << u <<"][" << v << "]="<< cplex.getValue( z[u][v]) << " "; Z.push_back(cplex.getValue( z[u][v])); } std::cout << "\n"; } std::cout <<"\n"; */ } // end try catch (IloException& e) { std::cerr << "Concert exception caught: " << e << std::endl; } catch (...) { std::cerr << "Unknown exception caught" << std::endl; } env.end(); return 0; }
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
void LpSolver::addObjective(string mode, CplexConverter& cplexConverter, IloModel model, IloNumVarArray x, IloRangeArray c){ // cerr << mode << endl; IloEnv env = model.getEnv(); if (mode == "MIN_SRC_COST"){ IloExpr cost(env); // add cost to all atomic edges for (int i = 0; i < cplexConverter.variables.size(); ++i){ cost += x[i] * cplexConverter.variables[i].interest_rate; } for(auto &atoIn : cplexConverter.src->atomicEdge_in){ int aeId = atoIn.second->atomicEdgeId; for (int j = 0; j < cplexConverter.atomicIdToVarIdDict[aeId].size(); j++){ // var Id int vId = cplexConverter.atomicIdToVarIdDict[aeId][j]; cost += cplexConverter.variables[vId].interest_rate * x[vId]; // cout << "adding " << cplexConverter.variables[vId].interest_rate // << " * " << vId << endl; } } model.add(IloMinimize(env, cost)); } else if (mode == "MIN_CREDIT_COST") { IloExpr cost(env); // add cost to all atomic edges for (int i = 0; i < cplexConverter.variables.size(); ++i){ cost += x[i] * cplexConverter.variables[i].interest_rate; } for (int i = 0; i < cplexConverter.variables.size(); ++i){ int aeId = cplexConverter.variables[i].atomicEdgeId; if (!cplexConverter.graph->atomicEdges[aeId]->isDebt){ cost += x[i]; } } model.add(IloMinimize(env, cost)); } else if (mode == "MIN_CREDIT_SRC") { IloExpr cost(env); for(auto &atoIn : cplexConverter.src->atomicEdge_in){ int aeId = atoIn.second->atomicEdgeId; for (int j = 0; j < cplexConverter.atomicIdToVarIdDict[aeId].size(); j++){ // var Id int vId = cplexConverter.atomicIdToVarIdDict[aeId][j]; cost += cplexConverter.variables[vId].interest_rate * x[vId]; if (!cplexConverter.graph->atomicEdges[aeId]->isDebt){ cost += x[vId]; } // cout << "adding " << cplexConverter.variables[vId].interest_rate // << " * " << vId << endl; } } model.add(IloMinimize(env, cost)); } else if (mode == "MIN_DEGREE_SRC") { IloExpr cost(env); for(auto &atoIn : cplexConverter.src->atomicEdge_in){ int aeId = atoIn.second->atomicEdgeId; AtomicEdge* atEdge = cplexConverter.graph->atomicEdges[aeId]; for (int j = 0; j < cplexConverter.atomicIdToVarIdDict[aeId].size(); j++){ // var Id int vId = cplexConverter.atomicIdToVarIdDict[aeId][j]; cost += cplexConverter.variables[vId].interest_rate * x[vId]; if (!atEdge->isDebt){ cost += atEdge->nodeTo->degree * x[vId]; } else { cost += atEdge->nodeFrom->degree * x[vId]; } // cout << "adding " << cplexConverter.variables[vId].interest_rate // << " * " << vId << endl; } } model.add(IloMinimize(env, cost)); } else if (mode == "MAX_IR_COST") { IloExpr cost(env); // add cost to all atomic edges for (int i = 0; i < cplexConverter.variables.size(); ++i){ cost += 100 - x[i] * cplexConverter.variables[i].interest_rate; } model.add(IloMinimize(env, cost)); } else if (mode == "MIN_SUMIR_COST") { IloExpr cost(env); // add cost to all atomic edges for (int i = 0; i < cplexConverter.variables.size(); ++i){ cost += x[i] * cplexConverter.variables[i].interest_rate; } model.add(IloMinimize(env, cost)); } else if (mode == "MIN_DEGREE_COST") { IloExpr cost(env); // add cost to all atomic edges for (int i = 0; i < cplexConverter.variables.size(); ++i){ cost += x[i] * cplexConverter.variables[i].interest_rate; } for (int i = 0; i < cplexConverter.variables.size(); ++i){ int aeId = cplexConverter.variables[i].atomicEdgeId; AtomicEdge* atEdge = cplexConverter.graph->atomicEdges[aeId]; for (int j = 0; j < cplexConverter.atomicIdToVarIdDict[aeId].size(); j++){ // var Id int vId = cplexConverter.atomicIdToVarIdDict[aeId][j]; if (!atEdge->isDebt){ cost += atEdge->nodeTo->degree * x[vId]; } else { cost += atEdge->nodeFrom->degree * x[vId]; } } } model.add(IloMinimize(env, cost)); } else { // default model.add(IloMinimize(env, 1)); } }
static void populatebyrow (IloModel model, IloNumVarArray x, IloRangeArray c) { IloEnv env = model.getEnv(); IloNumArray costs(env); IloNumArray time(env); IloNumArray product(env); int costs_array[] = {1,1,1,10,1,12,2,2,5,10}; int time_array[] = {10,1,7,3,2,3,2,3,7,1}; int product_array[] = {0,3,1,2,-2,0,0,0,0,0}; for(int i=0;i<10;i++) costs.add(costs_array[i]); for(int i=0;i<10;i++) time.add(time_array[i]); for(int i=0;i<10;i++) product.add(product_array[i]); x.add(IloBoolVar(env,"x12")); //0 x.add(IloBoolVar(env,"x24")); //1 x.add(IloBoolVar(env,"x46")); //2 x.add(IloBoolVar(env,"x13")); //3 x.add(IloBoolVar(env,"x32")); //4 x.add(IloBoolVar(env,"x35")); //5 x.add(IloBoolVar(env,"x56")); //6 x.add(IloBoolVar(env,"x25")); //7 x.add(IloBoolVar(env,"x34")); //8 x.add(IloBoolVar(env,"x45")); //9 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s2")); //10 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s3")); //11 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s4")); //12 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s5")); //13 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s1")); //14 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s6")); //15 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q2")); //16 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q3")); //17 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q4")); //18 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q5")); //19 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q1")); //20 x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q6")); //21 model.add(IloMinimize(env, costs[0]*x[0] + costs[1]*x[1] + costs[2]*x[2] + costs[3]*x[3] + costs[4]*x[4] + costs[5]*x[5] + costs[6]*x[6] + costs[7]*x[7] + costs[8]*x[8] + costs[9]*x[9])); c.add(x[0]+ x[3] == 1); // arcs sortant du noeud de depart c.add(x[2]+ x[6] == 1); // arcs entrant au noeud d arrivee c.add(x[1]+ x[7] - x[0] - x[4] == 0); c.add(x[8]+ x[5] + x[4] - x[3] == 0); c.add(x[9]+ x[2] - x[1] - x[8] == 0); c.add(x[6]- x[7] - x[5] - x[9] == 0); c.add(time[0]*x[0] + time[1]*x[1] + time[2]*x[2] + time[3]*x[3] + time[4]*x[4] + time[5]*x[5] + time[6]*x[6] + time[7]*x[7] + time[8]*x[8] + time[9]*x[9] <= 14); //c.add(product[0]*x[0] + product[1]*x[1] + product[2]*x[2] + product[3]*x[3] + product[4]*x[4] + product[5]*x[5] + product[6]*x[6] + product[7]*x[7] + product[8]*x[8] + product[9]*x[9] <= 4); c.add(x[14]+time[0]-1000*(1-x[0]) - x[10]<= 0); c.add(x[20]+product[0]-1000*(1-x[0]) - x[16]<= 0); c.add(x[10]+time[1]-1000*(1-x[1]) - x[12]<= 0); c.add(x[16]+product[1]-1000*(1-x[1]) - x[18]<= 0); c.add(x[18]-product[1]-1000*(1-x[1]) - x[16]<= 0); c.add(x[12]+time[2]-1000*(1-x[2]) - x[15]<= 0); c.add(x[18]+product[2]-1000*(1-x[2]) - x[21]<= 0); c.add(x[21]-product[2]-1000*(1-x[2]) - x[18]<= 0); c.add(x[14]+time[3]-1000*(1-x[3]) - x[11]<= 0); c.add(x[20]+product[3]-1000*(1-x[3]) - x[17]<= 0); c.add(x[17]-product[3]-1000*(1-x[3]) - x[20]<= 0); c.add(x[13]+time[6]-1000*(1-x[6]) - x[15]<= 0); c.add(x[19]+product[6]-1000*(1-x[6]) - x[21]<= 0); c.add(x[10]+time[7]-1000*(1-x[7]) - x[13]<= 0); c.add(x[16]+product[7]-1000*(1-x[7]) - x[19]<= 0); c.add(x[12]+time[9]-1000*(1-x[9]) - x[13]<= 0); c.add(x[18]+product[9]-1000*(1-x[9]) - x[19]<= 0); c.add(x[11]+time[4]-1000*(1-x[4]) - x[10] <=0); c.add(x[17]+product[4]-1000*(1-x[4]) - x[16]<= 0); c.add(x[16]-product[4]-1000*(1-x[4]) - x[17]<= 0); c.add(x[11]+time[8]-1000*(1-x[8]) - x[12]<= 0); c.add(x[17]+product[8]-1000*(1-x[8]) - x[18]<= 0); c.add(x[11]+time[5]-1000*(1-x[5]) - x[13]<= 0); c.add(x[17]+product[5]-1000*(1-x[5]) - x[19]<= 0); c.add(5 <= x[10] <= 7); c.add(2 <= x[11] <= 5); c.add(5 <= x[12] <= 9); c.add(0 <= x[13] <= 20); c.add(0 <= x[14] <= 0); c.add(0 <= x[15] <= 14); /* c.add(2 <= x[17] <= 4); c.add(0 <= x[16] <= 2); c.add(3 <= x[18] <= 4); c.add(0 <= x[19] <= 1000); //c.add(0 <= x[20] <= 0);*/ c.add(3 <= x[21] <= 4); c.add( x[20] == 1); model.add(c); }
ILOSTLBEGIN vector<double> solve_qp_cplex(QP* qp, bool& success) { vector<double> res(qp->num_var, 0); IloEnv env; try { IloModel model(env); // variables IloNumVarArray var(env); for (int i=0; i<qp->num_var; i++) { if (qp->binary_idx[i]==0) var.add(IloNumVar(env, qp->lb[i], qp->ub[i])); else var.add(IloNumVar(env, qp->lb[i], qp->ub[i], ILOINT)); } // constraints IloRangeArray con(env); //TODO remove these fake constraints for (int i=0; i<qp->num_var; i++) { con.add( var[i]<= 1e10); } // iterate over constraint matrix for (int i=0; i<qp->b.size(); i++) { vector<int>* idx = NULL; vector<float>* coef = NULL; int ret = qp->A.get(&idx, &coef, i); assert(idx!=NULL); assert(coef!=NULL); assert(ret>0); assert(idx->size()==coef->size()); IloNumExpr c_expr(env); for (int j=0; j<idx->size(); j++) { //printf("j:%i %.3f %i (num_var: %i)\n", j, coef->at(j), idx->at(j), qp->num_var); assert(idx->at(j)<qp->num_var); c_expr+= coef->at(j)*var[idx->at(j)]; } if (qp->eq_idx[i]>0) { con.add(c_expr == qp->b[i]); //env.out() << i << c_expr << "==" << qp->b[i] << endl; } else { con.add(c_expr <= qp->b[i]); //env.out() << i << c_expr << "<=" << qp->b[i] << endl; } } // objective IloNumExpr obj_expr(env); qp->Q.reset_it(); while (true) { int i=0; int j=0; float val = qp->Q.next(&i, &j); //printf("%i %i %.2f\n", i, j, val); if (i==-1) break; assert(i<qp->num_var && j<qp->num_var); obj_expr+= var[i] * var[j] * val; } for (int i=0; i<qp->F.size(); i++) { if (qp->F[i]!=0) obj_expr+= var[i] * qp->F[i]; } IloObjective obj(env, IloMinimize(env, obj_expr)); //model.add(IloMinimize(env, var[0] + 2 * var[1] + 3 * var[2] + var[3])); //env.out() << "objective: " << IloMinimize(env, obj_expr) << endl; //env.out() << "constraints: " << con << endl; // create model //model.add(var); model.add(con); model.add(obj); // solve... IloCplex cplex(model); cplex.solve(); IloNumArray vals(env); cplex.getValues(vals, var); //env.out() << "Values = " << vals << endl; //cplex.getSlacks(vals, con); //env.out() << "Slacks = " << vals << endl; env.out() << "Solution status = " << cplex.getStatus() << endl; env.out() << "Solution value = " << cplex.getObjValue() << endl; for (int i=0; i<qp->num_var; i++) res[i] = vals[i]; } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; success = false; } catch (...) { cerr << "Unknown exception caught" << endl; success = false; } env.end(); return res; }
/**************************************************程序入口****************************************************/ int main() { clock_t start,finish; double totaltime; start=clock(); try { define_data(env);//首先初始化全局变量 IloInvert(env,B0,B0l,Node-1);//求逆矩阵 /*************************************************************主问题目标函数*******************************************************/ IloNumExpr Cost(env); for(IloInt w=0;w<NW;++w) { Cost+=detaPw[w]; } Master_Model.add(IloMinimize(env,Cost)); //Master_Model.add(IloMaximize(env,Cost));//目标函数二先一 Cost.end(); /********************************************************机组出力上下限约束**************************************************/ IloNumExpr expr1(env),expr2(env); for(IloInt i=0;i<NG;++i) { expr1+=detaP[i]; } for(IloInt w=0;w<NW;++w) { expr2+=detaPw[w]; } Master_Model.add(expr1==expr2); expr1.end(); expr2.end(); for(IloInt i=0;i<NG;++i) { Master_Model.add(detaP[i]>=Unit[i][1]*u[i]-P1[i]); Master_Model.add(detaP[i]<=Unit[i][2]*u[i]-P1[i]); Master_Model.add(detaP[i]>=-detaa[i]); Master_Model.add(detaP[i]<=detaa[i]); } IloNumExprArray detaP_node(env,Node-1),detaPw_node(env,Node-1); IloNumExprArray Theta(env,Node); for(IloInt b=0;b<Node-1;++b) { detaP_node[b]=IloNumExpr(env); detaPw_node[b]=IloNumExpr(env); IloInt i=0; for(;i<NG;++i) { if(Unit[i][0]==b-1)break; } if(i<NG) { detaP_node[b]+=detaP[i]; } else { detaP_node[b]+=0; } if(Sw[b]>=0) { detaPw_node[b]+=detaPw[ Sw[b] ]; } else { detaPw_node[b]+=0; } } for(IloInt b=0;b<Node-1;++b) { Theta[b]=IloNumExpr(env); for(IloInt k=0;k<Node-1;++k) { Theta[b]+=B0l[b][k]*(detaP_node[k]+detaPw_node[k]); } } Theta[Node-1]=IloNumExpr(env); for(IloInt h=0;h<Branch;++h) { IloNumExpr exprTheta(env);//莫明其妙的错误 exprTheta+=(Theta[(IloInt)Info_Branch[h][0]-1]-Theta[(IloInt)Info_Branch[h][1]-1]); Master_Model.add(exprTheta<=Info_Branch[h][3]*(Info_Branch[h][4]-PL[h])); Master_Model.add(exprTheta>=Info_Branch[h][3]*(-Info_Branch[h][4]-PL[h])); exprTheta.end(); //两个相减的节点顺序没有影响么? } Theta.end(); detaP_node.end(); detaPw_node.end(); Master_Cplex.extract(Master_Model); Master_Cplex.solve(); if (Master_Cplex.getStatus() == IloAlgorithm::Infeasible)//输出结果 { output<<"Master Problem Have No Solution"<<endl; goto lable2; } /************************************************************输出显示过程**************************************************/ output<<endl<<"Min/Max:"<<Master_Cplex.getObjValue()<<endl; lable2: Master_Model.end(); Master_Cplex.end(); env.end(); } catch(IloException& ex)//异常捕获 { output<<"Error: "<<ex<<endl; } catch(...) { output<<"Error: Unknown exception caught!" << endl; } finish=clock(); totaltime=(double)(finish-start)/CLOCKS_PER_SEC; output<<"totaltime: "<<totaltime<<"s"<<endl<<endl; output.close(); return 0; }
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) { IloEnv env; try { IloInt i, j; const char* filename; if (argc > 1) filename = argv[1]; else filename = "../../../examples/data/etsp.dat"; ifstream f(filename, ios::in); if (!f) { cerr << "No such file: " << filename << endl; throw(1); } IntMatrix activityOnAResource(env); NumMatrix duration(env); IloNumArray jobDueDate(env); IloNumArray jobEarlinessCost(env); IloNumArray jobTardinessCost(env); f >> activityOnAResource; f >> duration; f >> jobDueDate; f >> jobEarlinessCost; f >> jobTardinessCost; IloInt nbJob = jobDueDate.getSize(); IloInt nbResource = activityOnAResource.getSize(); IloModel model(env); // Create start variables NumVarMatrix s(env, nbJob); for (j = 0; j < nbJob; j++) { s[j] = IloNumVarArray(env, nbResource, 0.0, Horizon); } // State precedence constraints for (j = 0; j < nbJob; j++) { for (i = 1; i < nbResource; i++) { model.add(s[j][i] >= s[j][i-1] + duration[j][i-1]); } } // State disjunctive constraints for each resource for (i = 0; i < nbResource; i++) { IloInt end = nbJob - 1; for (j = 0; j < end; j++) { IloInt a = activityOnAResource[i][j]; for (IloInt k = j + 1; k < nbJob; k++) { IloInt b = activityOnAResource[i][k]; model.add(s[j][a] >= s[k][b] + duration[k][b] || s[k][b] >= s[j][a] + duration[j][a]); } } } // The cost is the sum of earliness or tardiness costs of each job IloInt last = nbResource - 1; IloExpr costSum(env); for (j = 0; j < nbJob; j++) { costSum += IloPiecewiseLinear(s[j][last] + duration[j][last], IloNumArray(env, 1, jobDueDate[j]), IloNumArray(env, 2, -jobEarlinessCost[j], jobTardinessCost[j]), jobDueDate[j], 0); } model.add(IloMinimize(env, costSum)); costSum.end(); IloCplex cplex(env); cplex.extract(model); cplex.setParam(IloCplex::Param::Emphasis::MIP, 4); if (cplex.solve()) { cout << "Solution status: " << cplex.getStatus() << endl; cout << " Optimal Value = " << cplex.getObjValue() << endl; } } catch (IloException& ex) { cerr << "Error: " << ex << endl; } catch (...) { cerr << "Error" << endl; } env.end(); return 0; }
// This function creates the following model: // Minimize // obj: x1 + x2 + x3 + x4 + x5 + x6 // Subject To // c1: x1 + x2 + x5 = 8 // c2: x3 + x5 + x6 = 10 // q1: [ -x1^2 + x2^2 + x3^2 ] <= 0 // q2: [ -x4^2 + x5^2 ] <= 0 // Bounds // x2 Free // x3 Free // x5 Free // End // which is a second order cone program in standard form. // The function returns objective, variables and constraints in the // values obj, vars and rngs. // The function also sets up cone so that for a column j we have // cone[j] >= 0 Column j is in a cone constraint and is the // cone's head variable. // cone[j] == NOT_CONE_HEAD Column j is in a cone constraint but is // not the cone's head variable.. // cone[j] == NOT_IN_CONE Column j is not contained in any cone constraint. static void createmodel (IloModel& model, IloObjective &obj, IloNumVarArray &vars, IloRangeArray &rngs, IloIntArray& cone) { // The indices we assign as user objects to the modeling objects. // We define them as static data so that we don't have to worry about // dynamic memory allocation/leakage. static int indices[] = { 0, 1, 2, 3, 4, 5, 6 }; IloEnv env = model.getEnv(); // Create variables. IloNumVar x1(env, 0, IloInfinity, "x1"); IloNumVar x2(env, -IloInfinity, IloInfinity, "x2"); IloNumVar x3(env, -IloInfinity, IloInfinity, "x3"); IloNumVar x4(env, 0, IloInfinity, "x4"); IloNumVar x5(env, -IloInfinity, IloInfinity, "x5"); IloNumVar x6(env, 0, IloInfinity, "x6"); // Create objective function and immediately store it in return value. obj = IloMinimize(env, x1 + x2 + x3 + x4 + x5 + x6); // Create constraints. IloRange c1(env, 8, x1 + x2 + x5, 8, "c1"); IloRange c2(env, 10, x3 + x5 + x6, 10, "c2"); IloRange q1(env, -IloInfinity, -x1*x1 + x2*x2 + x3*x3, 0, "q1"); cone.add(2); // x1, cone head of constraint at index 2 cone.add(NOT_CONE_HEAD); // x2 cone.add(NOT_CONE_HEAD); // x3 IloRange q2(env, -IloInfinity, -x4*x4 + x5*x5, 0, "q2"); cone.add(3); // x4, cone head of constraint at index 3 cone.add(NOT_CONE_HEAD); // x5 cone.add(NOT_IN_CONE); // x6 // Setup model. model.add(obj); model.add(obj); model.add(c1); model.add(c2); model.add(q1); model.add(q2); // Setup return values. vars.add(x1); vars.add(x2); vars.add(x3); vars.add(x4); vars.add(x5); vars.add(x6); rngs.add(c1); rngs.add(c2); rngs.add(q1); rngs.add(q2); // We set the user object for each modeling object to its index in the // respective array. This makes the code in checkkkt a little simpler. for (IloInt i = 0; i < vars.getSize(); ++i) vars[i].setObject(&indices[i]); for (IloInt i = 0; i < rngs.getSize(); ++i) rngs[i].setObject(&indices[i]); }
Example(IloEnv env) : nblocks(0), model(env), vars(env), ranges(env) { // Model data. // fixed[] is the fixed cost for opening a facility, // cost[i,j] is the cost for serving customer i from facility j. static double const fixed[] = { 2.0, 3.0, 3.0 }; static double const cost[] = { 2.0, 3.0, 4.0, 5.0, 7.0, 4.0, 3.0, 1.0, 2.0, 6.0, 5.0, 4.0, 2.0, 1.0, 3.0 }; #define NFACTORY ((CPXDIM)(sizeof(fixed) / sizeof(fixed[0]))) #define NCUSTOMER ((CPXDIM)((sizeof(cost) / sizeof(cost[0])) / NFACTORY)) nblocks = NCUSTOMER; IloExpr obj(env); // Create integer y variables. IloNumVarArray y(env); for (IloInt f = 0; f < NFACTORY; ++f) { std::stringstream s; s << "y" << f; IloIntVar v(env, 0, 1, s.str().c_str()); obj += fixed[f] * v; objMap[v] = fixed[f]; y.add(v); blockMap.insert(BlockMap::value_type(v, -1)); intersectMap.insert(IntersectMap::value_type(v, RowSet())); } // Create continuous x variables. IloNumVarArray x(env); for (IloInt f = 0; f < NFACTORY; ++f) { for (IloInt c = 0; c < NCUSTOMER; ++c) { std::stringstream s; s << "x" << f << "#" << c; IloNumVar v(env, 0.0, IloInfinity, s.str().c_str()); obj += v * cost[f * NCUSTOMER + c]; objMap[v] = cost[f * NCUSTOMER + c]; x.add(v); blockMap.insert(BlockMap::value_type(v, c)); intersectMap.insert(IntersectMap::value_type(v, RowSet())); } } vars.add(y); vars.add(x); model.add(vars); // Add objective function. model.add(IloMinimize(env, obj, "obj")); objSense = IloObjective::Minimize; obj.end(); // Satisfy each customer's demand. for (IloInt c = 0; c < NCUSTOMER; ++c) { std::stringstream s; s << "c1_" << c; IloRange r(env, 1.0, IloInfinity, s.str().c_str()); IloExpr lhs(env); for (IloInt f = 0; f < NFACTORY; ++f) { lhs += x[f * NCUSTOMER + c]; intersectMap[x[f * NCUSTOMER + c]].insert(r); } r.setExpr(lhs); ranges.add(r); lhs.end(); } // A factory must be open if we service from it. for (IloInt c = 0; c < NCUSTOMER; ++c) { for (IloInt f = 0; f < NFACTORY; ++f) { std::stringstream s; s << "c2_" << c << "#" << f; IloRange r(env, 0.0, IloInfinity, s.str().c_str()); intersectMap[x[f * NCUSTOMER + c]].insert(r); intersectMap[y[f]].insert(r); r.setExpr(-x[f * NCUSTOMER + c] + y[f]); ranges.add(r); } } // Capacity constraint. IloRange r(env, -IloInfinity, NFACTORY - 1, "c3"); IloExpr lhs(env); for (IloInt f = 0; f < NFACTORY; ++f) { lhs += y[f]; intersectMap[y[f]].insert(r); } r.setExpr(lhs); ranges.add(r); lhs.end(); model.add(ranges); #undef NFACTORY #undef NCUSTOMER }
int CProblem::setModel() { //time_t start, end; numvar = 1+n; // lambda + all c; IloEnv env; try { IloModel model(env); IloCplex cplex(env); /*Variables*/ IloNumVar lambda(env, "lambda"); IloNumVarArray c(env, n);// for (unsigned int u=0; u<n; u++) { std::stringstream ss; ss << u; std::string str = "c" + ss.str(); c[u]=IloNumVar(env, str.c_str()); } IloArray<IloIntVarArray> z(env,n); for (unsigned int u=0; u<n; u++) { z[u]= IloIntVarArray(env, n); for (unsigned int v=0; v<n; v++) { std::stringstream ss; ss << u; ss << v; std::string str = "z" + ss.str(); z[u][v] = IloIntVar(env, 0, 1, str.c_str()); } } /* Constant M*/ int M=n*max_d; UB = M; /* Objective*/ model.add(IloMinimize(env, lambda)); //model.add(IloMinimize(env, IloSum(c))); /*Constrains*/ model.add(lambda - UB <= 0); /* d=function of the distance */ IloArray<IloNumArray> Par_d(env,n); for (unsigned int u=0; u<n; u++) { Par_d[u]=IloNumArray(env,n); for (unsigned int v=0; v<n; v++) { Par_d[u][v]=d[u][v]; } } for (unsigned u=0; u<n; u++) { for (unsigned v=0; v<u; v++) { model.add(c[v]-c[u]+M* z[u][v] >= Par_d[u][v] ); model.add(c[u]-c[v]+M*(1-z[u][v]) >= Par_d[u][v]); numvar++; // + z[u][v] } } /* for (unsigned i=0; i<sqrt(n)-1; i=i+1) { for (unsigned j=0; j<sqrt(n)-1; j=j+1) { //square lattice model.add (c[i*sqrt(n)+j] +c[i*sqrt(n)+j+1] + c[(i+1)*sqrt(n)+j] +c[(i+1)*sqrt(n)+j+1]>= 16-4*sqrt(2)); // Bedingung fuer Quadratischen Gridgraph und d(x) = 3-x // // triangular lattice // model.add (c[i*5+j]+c[i*5+j+1] + // c[(i+1)+j] >= 4); // Bedingung fuer Quadratischen Gridgraph und d(x) = 3-x // model.add (c[i*sqrt(n)+j]+c[i*sqrt(n)+j+1] + // c[(i+1)*sqrt(n)+j]+c[(i+1)*sqrt(n)+j+1] >= 22 - 4*sqrt(2)); // Bedingung fuer Quadratischen Gridgraph und d(x) = 4-x } } */ /* for (unsigned i=0; i<sqrt(n)-2; i+=3) { for (unsigned j=0; j<sqrt(n)-2; j+=3) { // model.add (c[i*sqrt(n)+j] + c[i*sqrt(n)+j+1] + c[i*sqrt(n)+j+2] + // c[(i+1)*sqrt(n)+j]+ c[(i+1)*sqrt(n)+j+1]+ c[(i+1)*sqrt(n)+j+2] + // c[(i+2)*sqrt(n)+j]+ c[(i+2)*sqrt(n)+j+1]+ c[(i+2)*sqrt(n)+j+2] // >= 60-17*sqrt(2)-3*sqrt(5)); // Bedingung fuer Quadratischen Gridgraph und d(x) = 3-x // model.add (c[i*sqrt(n)+j] + c[i*sqrt(n)+j+1] + c[i*sqrt(n)+j+2] + // c[(i+1)*sqrt(n)+j]+ c[(i+1)*sqrt(n)+j+1]+ c[(i+1)*sqrt(n)+j+2] + // c[(i+2)*sqrt(n)+j]+ c[(i+2)*sqrt(n)+j+1]+ c[(i+2)*sqrt(n)+j+2] // >= 82-8*sqrt(2)-2*sqrt(5)); // Bedingung fuer Quadratischen Gridgraph und d(x) = 4-x } } */ for (unsigned int v=0; v<n; v++) { IloExpr expr; model.add (c[v] <= lambda); model.add (c[v] >= 0); expr.end(); } std::cout << "Number of variables " << numvar << "\n"; /* solve the Model*/ cplex.extract(model); cplex.exportModel("L-Labeling.lp"); /* start = clock(); int solveError = cplex.solve(); end = clock (); */ IloTimer timer(env); timer.start(); int solveError = cplex.solve(); timer.stop(); if ( !solveError ) { std::cout << "STATUS : "<< cplex.getStatus() << "\n"; env.error() << "Failed to optimize LP \n"; exit(1); } //Info.time = (double)(end-start)/(double)CLOCKS_PER_SEC; Info.time = timer.getTime(); std::cout << "STATUS : "<< cplex.getStatus() << "\n"; /* get the solution*/ env.out() << "Solution status = " << cplex.getStatus() << "\n"; numconst = cplex.getNrows(); env.out() << " Number of constraints = " << numconst << "\n"; lambda_G_d=cplex.getObjValue(); env.out() << "Solution value = " << lambda_G_d << "\n"; for (unsigned int u=0; u<n; u++) { C.push_back(cplex.getValue(c[u])); std::cout << "c(" << u << ")=" << C[u]<< " "; } std::cout <<"\n"; /* for (unsigned int u=0; u<n; u++) { for (unsigned int v=0; v<u; v++) { std::cout<< "z[" << u <<"][" << v << "]="<< cplex.getValue( z[u][v]) << " "; Z.push_back(cplex.getValue( z[u][v])); } std::cout << "\n"; } std::cout <<"\n"; */ } // end try catch (IloException& e) { std::cerr << "Concert exception caught: " << e << std::endl; } catch (...) { std::cerr << "Unknown exception caught" << std::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; }