ILOHEURISTICCALLBACK1(Rounddown, IloNumVarArray, vars) { IntegerFeasibilityArray feas; IloNumArray obj; IloNumArray x; try { feas = IntegerFeasibilityArray(getEnv()); obj = IloNumArray(getEnv()); x = IloNumArray(getEnv()); getFeasibilities(feas, vars); getObjCoefs (obj , vars); getValues (x , vars); IloNum objval = getObjValue(); IloInt cols = vars.getSize(); for (IloInt j = 0; j < cols; j++) { // Set the fractional variable to zero and update the objective value if ( feas[j] == Infeasible ) { objval -= x[j] * obj[j]; x[j] = 0.0; } } setSolution(vars, x, objval); } catch (...) { feas.end(); obj.end(); x.end(); throw; } feas.end(); obj.end(); x.end(); }
ILOBRANCHCALLBACK1(MyBranch, IloNumVarArray, vars) { if ( getBranchType() != BranchOnVariable ) return; // Branch on var with largest objective coefficient // among those with largest infeasibility IloNumArray x; IloNumArray obj; IntegerFeasibilityArray feas; try { x = IloNumArray(getEnv()); obj = IloNumArray(getEnv()); feas = IntegerFeasibilityArray(getEnv()); getValues(x, vars); getObjCoefs(obj, vars); getFeasibilities(feas, vars); IloInt bestj = -1; IloNum maxinf = 0.0; IloNum maxobj = 0.0; IloInt cols = vars.getSize(); for (IloInt j = 0; j < cols; j++) { if ( feas[j] == Infeasible ) { IloNum xj_inf = x[j] - IloFloor (x[j]); if ( xj_inf > 0.5 ) xj_inf = 1.0 - xj_inf; if ( xj_inf >= maxinf && (xj_inf > maxinf || IloAbs (obj[j]) >= maxobj) ) { bestj = j; maxinf = xj_inf; maxobj = IloAbs (obj[j]); } } } if ( bestj >= 0 ) { makeBranch(vars[bestj], x[bestj], IloCplex::BranchUp, getObjValue()); makeBranch(vars[bestj], x[bestj], IloCplex::BranchDown, getObjValue()); } } catch (...) { x.end(); obj.end(); feas.end(); throw; } x.end(); obj.end(); feas.end(); }
// Implementation class for the user-defined lazy constraint callback. // The function BendersLazyCallback allows to add Benders' cuts as lazy constraints. // ILOLAZYCONSTRAINTCALLBACK5(BendersLazyCallback, Arcs, x, IloCplex, workerCplex, IloNumVarArray, v, IloNumVarArray, u, IloObjective, workerObj) { IloInt i; IloEnv masterEnv = getEnv(); IloInt numNodes = x.getSize(); // Get the current x solution IloNumArray2 xSol(masterEnv, numNodes); for (i = 0; i < numNodes; ++i) { xSol[i] = IloNumArray(masterEnv); getValues(xSol[i], x[i]); } // Benders' cut separation IloExpr cutLhs(masterEnv); IloNum cutRhs; IloBool sepStat = separate(x, xSol, workerCplex, v, u, workerObj, cutLhs, cutRhs); if ( sepStat ) { add(cutLhs >= cutRhs).end(); } // Free memory cutLhs.end(); for (i = 0; i < numNodes; ++i) xSol[i].end(); xSol.end(); return; } // END BendersLazyCallback
DataNumMatrix::DataNumMatrix(IloEnv env,int n, int m){ this->Matrix = IloArray<IloNumArray> (env,n); for(int i = 0; i < n; i++){ this->Matrix[i] = IloNumArray(env,m); } this->n = n; this->m = m; this->env = env; }
ILOCPLEXGOAL1(MyBranchGoal, IloNumVarArray, vars) { IloNumArray x; IloNumArray obj; IntegerFeasibilityArray feas; x = IloNumArray(getEnv()); obj = IloNumArray(getEnv()); feas = IntegerFeasibilityArray(getEnv()); getValues(x, vars); getObjCoefs(obj, vars); getFeasibilities(feas, vars); IloInt bestj = -1; IloNum maxinf = 0.0; IloNum maxobj = 0.0; IloInt cols = vars.getSize(); for (IloInt j = 0; j < cols; j++) { if ( feas[j] == Infeasible ) { IloNum xj_inf = x[j] - IloFloor (x[j]); if ( xj_inf > 0.5 ) xj_inf = 1.0 - xj_inf; if ( xj_inf >= maxinf && (xj_inf > maxinf || IloAbs (obj[j]) >= maxobj) ) { bestj = j; maxinf = xj_inf; maxobj = IloAbs (obj[j]); } } } IloCplex::Goal res; if ( bestj >= 0 ) { res = AndGoal(OrGoal(vars[bestj] >= IloFloor(x[bestj])+1, vars[bestj] <= IloFloor(x[bestj])), this); } x.end(); obj.end(); feas.end(); return res; }
void setData(const IloEnv env) { consumption[0] = IloNumArray(env, nbProds, 0.5, 0.4, 0.3); consumption[1] = IloNumArray(env, nbProds, 0.2, 0.4, 0.6); capacity = IloNumArray(env, nbResources, 20.0, 40.0); demand = IloNumArray(env, nbProds, 100.0, 200.0, 300.0); insideCost = IloNumArray(env, nbProds, 0.6, 0.8, 0.3); outsideCost = IloNumArray(env, nbProds, 0.8, 0.9, 0.4); }
DataNumMatrix::DataNumMatrix(const DataNumMatrix& copy_Matrix){ this->n = copy_Matrix.n; this->m = copy_Matrix.m; this->env = copy_Matrix.env; this->Matrix = IloArray<IloNumArray> (this->env,this->n); for(int i = 0; i < this->n; i++){ this->Matrix[i] = IloNumArray(this->env,this->m); } for(int i = 1; i <= this->n; i++){ for(int j = 1; j <= this->m; j++){ Coordinate coord(i,j); this->Matrix[i-1][j-1]= copy_Matrix.get(coord); } } }
void define_data(IloEnv env) { nbElements = 3; nbRaw = 2; nbScrap = 2; nbIngot = 1; alloy = 71; nm = IloNumArray(env, nbElements, 22.0, 10.0, 13.0); nr = IloNumArray(env, nbRaw, 6.0, 5.0); ns = IloNumArray(env, nbScrap, 7.0, 8.0); ni = IloNumArray(env, nbIngot, 9.0); p = IloNumArray(env, nbElements, 0.05, 0.30, 0.60); P = IloNumArray(env, nbElements, 0.10, 0.40, 0.80); PRaw = IloNumArray2(env, nbElements); PScrap = IloNumArray2(env, nbElements); PIngot = IloNumArray2(env, nbElements); PRaw[0] = IloNumArray(env, nbRaw, 0.20, 0.01); PRaw[1] = IloNumArray(env, nbRaw, 0.05, 0.00); PRaw[2] = IloNumArray(env, nbRaw, 0.05, 0.30); PScrap[0] = IloNumArray(env, nbScrap, 0.00, 0.01); PScrap[1] = IloNumArray(env, nbScrap, 0.60, 0.00); PScrap[2] = IloNumArray(env, nbScrap, 0.40, 0.70); PIngot[0] = IloNumArray(env, nbIngot, 0.10); PIngot[1] = IloNumArray(env, nbIngot, 0.45); PIngot[2] = IloNumArray(env, nbIngot, 0.45); }
int main(int argc, char **argv) { IloEnv masterEnv; IloEnv workerEnv; try { const char* fileName = "../../../examples/data/atsp.dat"; // Check the command line arguments if ( argc != 2 && argc != 3) { usage (argv[0]); throw (-1); } if ( (argv[1][0] != '1' && argv[1][0] != '0') || argv[1][1] != '\0' ) { usage (argv[0]); throw (-1); } IloBool separateFracSols = ( argv[1][0] == '0' ? IloFalse : IloTrue ); masterEnv.out() << "Benders' cuts separated to cut off: "; if ( separateFracSols ) { masterEnv.out() << "Integer and fractional infeasible solutions." << endl; } else { masterEnv.out() << "Only integer infeasible solutions." << endl; } if ( argc == 3 ) fileName = argv[2]; // Read arc_costs from data file (17 city problem) IloNumArray2 arcCost(masterEnv); ifstream data(fileName); if ( !data ) throw(-1); data >> arcCost; data.close(); // create master ILP IloModel masterMod(masterEnv, "atsp_master"); IloInt numNodes = arcCost.getSize(); Arcs x(masterEnv, numNodes); createMasterILP(masterMod, x, arcCost); // Create worker IloCplex algorithm and worker LP for Benders' cuts separation IloCplex workerCplex(workerEnv); IloNumVarArray v(workerEnv); IloNumVarArray u(workerEnv); IloObjective workerObj(workerEnv); createWorkerLP(workerCplex, v, u, workerObj, numNodes); // Set up the cut callback to be used for separating Benders' cuts IloCplex masterCplex(masterMod); masterCplex.setParam(IloCplex::Param::Preprocessing::Presolve, IloFalse); // Set the maximum number of threads to 1. // This instruction is redundant: If MIP control callbacks are registered, // then by default CPLEX uses 1 (one) thread only. // Note that the current example may not work properly if more than 1 threads // are used, because the callback functions modify shared global data. // We refer the user to the documentation to see how to deal with multi-thread // runs in presence of MIP control callbacks. masterCplex.setParam(IloCplex::Param::Threads, 1); // Turn on traditional search for use with control callbacks masterCplex.setParam(IloCplex::Param::MIP::Strategy::Search, IloCplex::Traditional); masterCplex.use(BendersLazyCallback(masterEnv, x, workerCplex, v, u, workerObj)); if ( separateFracSols ) masterCplex.use(BendersUserCallback(masterEnv, x, workerCplex, v, u, workerObj)); // Solve the model and write out the solution if ( masterCplex.solve() ) { IloAlgorithm::Status solStatus= masterCplex.getStatus(); masterEnv.out() << endl << "Solution status: " << solStatus << endl; masterEnv.out() << "Objective value: " << masterCplex.getObjValue() << endl; if ( solStatus == IloAlgorithm::Optimal ) { // Write out the optimal tour IloInt i, j; IloNumArray2 sol(masterEnv, numNodes); IloIntArray succ(masterEnv, numNodes); for (j = 0; j < numNodes; ++j) succ[j] = -1; for (i = 0; i < numNodes; i++) { sol[i] = IloNumArray(masterEnv); masterCplex.getValues(sol[i], x[i]); for(j = 0; j < numNodes; j++) { if ( sol[i][j] > 1e-03 ) succ[i] = j; } } masterEnv.out() << "Optimal tour:" << endl; i = 0; while ( succ[i] != 0 ) { masterEnv.out() << i << ", "; i = succ[i]; } masterEnv.out() << i << endl; } else { masterEnv.out() << "Solution status is not Optimal" << endl; } } else { masterEnv.out() << "No solution available" << endl; } } catch (const IloException& e) { cerr << "Exception caught: " << e << endl; } catch (...) { cerr << "Unknown exception caught!" << endl; } // Close the environments masterEnv.end(); workerEnv.end(); return 0; } // END main
int main(int argc, char **argv) { clock_t t1, t2; t1 = clock(); IloEnv env; IloModel model(env); IloCplex cplex(model); /************************** Defining the parameters ************************************/ IloInt N; //No. of nodes IloInt M; //No. of calls Num2DMatrix links(env); //Defines the topology of the network IloNumArray call_demand(env); //link bandwidth requirement of each call IloNumArray call_revenue(env); //revenue generated from the call IloNumArray call_origin(env); //origin node index of each call IloNumArray call_destination(env); //destination node index of each call Num2DMatrix Q(env); //Bandwidth capacity of each link Num2DMatrix sigma(env); //Standard deviation of service times on link (i,j) Num2DMatrix cv(env); //coefficient of variation of service times on the link (i,j) IloNum C; //Unit queueing delay cost per unit time IloNumArray R_approx_init(env); ifstream fin; const char* filename = "BPP_data_sample - Copy.txt"; if (argc > 1) filename = argv[1]; fin.open(filename); //fin.open("BPP_10node_navneet.txt"); fin >> links >> call_origin >> call_destination >> call_demand >> call_revenue >> Q >> cv >> R_approx_init >> C ; cout << "Reading Data from the file - "<<filename<<endl; N = links.getSize(); M = call_origin.getSize(); IloInt H = R_approx_init.getSize(); Num3DMatrix R_approx(env, N); //The tangential linear function approximation to R. for (IloInt i=0; i<N; i++) { R_approx[i] = Num2DMatrix(env, N); for (IloInt j=0; j<N; j++) { R_approx[i][j] = IloNumArray(env, H); for (IloInt h=0; h<H; h++) R_approx[i][j][h] = R_approx_init[h]; } } /************************** Defining the parameters ENDS ************************************/ /************* Defining the variables defined in the model formulation **********************/ IloNumVarArray Y(env, M, 0, 1, ILOINT); //Variable to define whether a call m is routed or not IloNumArray Y_sol(env, M); //Solution values NumVar3DMatrix X(env, N); //Variable to define whether a call m is routed along path i-j Num3DMatrix X_sol(env, N); for (IloInt i=0; i<N; i++) { X[i] = NumVar2DMatrix(env, N); X_sol[i] = Num2DMatrix(env, N); for (IloInt j=0; j<N; j++) { X[i][j] = IloNumVarArray(env, M, 0, 1, ILOINT); X_sol[i][j] = IloNumArray(env, M); } } NumVar3DMatrix W(env, N); //Variable to define whether a call m is routed along path i-j for (IloInt i=0; i<N; i++) { W[i] = NumVar2DMatrix(env, N); for (IloInt j=0; j<N; j++) W[i][j] = IloNumVarArray(env, M, 0, 1, ILOINT); } NumVar2DMatrix R(env, (IloInt)N); //The linearization Variable for (IloInt i=0; i<N; i++) R[i] = IloNumVarArray(env, (IloInt)N, 0, IloInfinity, ILOFLOAT); /************* Defining the variables defined in the model formulation ENDS *****************/ /**************************** Defining the Constraints *******************************/ // Constraint #1 : Flow Conservation Constraint for (IloInt m=0; m<M; m++) { for (IloInt i=0; i<N; i++) { IloExpr constraint1(env); for (IloInt j=0; j<N; j++) { if (links[i][j] == 1) constraint1 += W[i][j][m]; } for (IloInt j=0; j<N; j++) { if (links[j][i] == 1) constraint1 += -W[j][i][m]; } if (i == call_origin[m]) model.add(constraint1 == Y[m]); else if (i == call_destination[m]) model.add(constraint1 == -Y[m]); else model.add(constraint1 == 0); constraint1.end(); } } // Constraint #2 : for (IloInt m=0; m<M; m++) { for (IloInt i=0; i<N; i++) { for (IloInt j=0; j<N; j++) { if (links[i][j] == 1) model.add(W[i][j][m] + W[j][i][m] <= X[i][j][m]); } } } // Constraint #3 : Link Capacity Constraint for (IloInt i=0; i<N; i++) { for (IloInt j=i+1; j<N; j++) { if (links[i][j] == 1) { IloExpr constraint3(env); for (IloInt m=0; m<M; m++) constraint3 += call_demand[m]*X[i][j][m]; model.add(constraint3 <= Q[i][j]); constraint3.end(); } } } // Constraint #4 : Defining the constraint for initial values of R_approx, // Cuts must be added during the iterations whenever the values are updated for (IloInt i=0; i<N; i++) { for (IloInt j=i+1; j<N; j++) { if (links[i][j] == 1) { for (IloInt h=0; h<H; h++) { IloExpr constraint4_lhs(env); IloNum constraint4_rhs = 0; for (IloInt m=0; m<M; m++) constraint4_lhs += call_demand[m]*X[i][j][m]; constraint4_lhs -= (Q[i][j]/((1+R_approx[i][j][h])*(1+R_approx[i][j][h])))*R[i][j]; constraint4_rhs = Q[i][j]*((R_approx[i][j][h]/(1+R_approx[i][j][h])) * (R_approx[i][j][h]/(1+R_approx[i][j][h]))); model.add(constraint4_lhs <= constraint4_rhs); constraint4_lhs.end(); } } } } /************************** Defining the Constraints ENDS ****************************/ /************************ Defining the Objective Function ****************************/ IloExpr Objective(env); IloExpr Obj_expr1(env); IloExpr Obj_expr2(env); for (IloInt m=0; m<M; m++) Obj_expr1 += call_revenue[m]*Y[m]; for (IloInt i=0; i<N; i++) { for (IloInt j=i+1; j<N; j++) { if (links[i][j] == 1) { Obj_expr2 += (1+cv[i][j] * cv[i][j])*R[i][j]; for (IloInt m=0; m<M; m++) Obj_expr2 += ((1-cv[i][j] * cv[i][j])/Q[i][j])*call_demand[m]*X[i][j][m]; } } } Objective += Obj_expr1 - 0.5*C*Obj_expr2; model.add(IloMaximize(env, Objective)); //model.add(IloMinimize(env, -Objective)); Objective.end(); Obj_expr1.end(); Obj_expr2.end(); /********************** Defining the Objective Function ENDS **************************/ IloNum eps = cplex.getParam(IloCplex::EpInt); IloNum UB = IloInfinity; IloNum LB = -IloInfinity; /***************** Solve ***********************/ do { cplex.setParam(IloCplex::MIPInterval, 5); cplex.setParam(IloCplex::NodeFileInd ,2); cplex.setOut(env.getNullStream()); cplex.exportModel("BPP_model.lp"); if(!cplex.solve()) { cout << "Infeasible"<<endl; system("pause"); } else { for (IloInt m=0; m<M; m++) { if (cplex.getValue(Y[m]) > eps) { cout << "Call(m) = "<<m+1<<" : "<<call_origin[m]+1<<" --> "<<call_destination[m]+1 <<"; demand = "<<call_demand[m]<<endl; cout << "Path : "; for (IloInt i=0; i<N; i++) { for (IloInt j=i+1; j<N; j++) { if (links[i][j] == 1) { if (cplex.getValue(X[i][j][m]) > eps) { X_sol[i][j][m] = 1; cout <<i+1<<"-"<<j+1<<"; "; } } } } cout << endl << endl; } } //system("pause"); } UB = min(UB, cplex.getObjValue()); IloNum lbound = 0; for (IloInt m=0; m<M; m++) if(cplex.getValue(Y[m]) > eps) lbound += call_revenue[m]; for (IloInt i=0; i<N; i++) { for (IloInt j=i+1; j<N; j++) { if (links[i][j] == 1) { IloNum lbound_temp1 = 0; IloNum lbound_temp2 = 0; for (IloInt m=0; m<M; m++) lbound_temp1 += call_demand[m]*X_sol[i][j][m]; lbound_temp2 = 0.5*(1+cv[i][j]*cv[i][j]) * (lbound_temp1*lbound_temp1) / (Q[i][j]*(Q[i][j]-lbound_temp1)); lbound_temp2 += lbound_temp1 / Q[i][j]; lbound -= C*lbound_temp2; } } } LB = max(LB, lbound); Num2DMatrix R_approx_new(env, N); for (IloInt i=0; i<N; i++) R_approx_new[i] = IloNumArray(env, N); for (IloInt i=0; i<N; i++) { for (IloInt j=i+1; j<N; j++) { if (links[i][j] == 1) { IloExpr cut_lhs(env); IloNum cut_rhs = 0; IloNum cut_temp = 0; for (IloInt m=0; m<M; m++) { cut_temp += call_demand[m]*X_sol[i][j][m]; } R_approx_new[i][j] = cut_temp / (Q[i][j] - cut_temp); //cout << "R_approx_new = "<<R_approx_new<<endl; for (IloInt m=0; m<M; m++) cut_lhs += call_demand[m]*X[i][j][m]; cut_lhs -= (Q[i][j]/((1+R_approx_new[i][j])*(1+R_approx_new[i][j])))*R[i][j]; cut_rhs = Q[i][j]*((R_approx_new[i][j]/(1+R_approx_new[i][j])) * (R_approx_new[i][j]/(1+R_approx_new[i][j]))); model.add(cut_lhs <= cut_rhs); cut_lhs.end(); } } } cout << "UB = "<<UB<<endl; cout << "LB = "<<LB<<endl; cout << "Gap (%) = "<<(UB-LB)*100/LB<<endl; //system("pause"); }while ((UB-LB)/UB > eps); t2 = clock(); float secs = (float)t2 - (float)t1; secs = secs / CLOCKS_PER_SEC; cout << "CPUTIME = "<<secs <<endl<<endl; }
void define_data(IloEnv env) { string line(" "); ifstream myfile ("/home/DavidRC/data.txt"); int i=0; int j=0; int x=0; int y=0; if (myfile.is_open()) { i=0; j=0; getline(myfile,line); n=atoi(line.c_str()); IloNumArray l(env,n); NumMatrix w(env,n); for(i=0; i<n; i++) { w[i]=IloNumArray(env,n); } getline (myfile,line); istringstream iss1(line); while (iss1 && j<n) { string subs; iss1 >> subs; string temp=subs; if(temp.compare("")==0) { continue; } else { l[j]=atoi(subs.c_str()); } j++; } exit(1); i=0; j=0; while ( getline (myfile,line) && i<n) { istringstream iss2(line); j=0; while (iss2 && j<n) { string subs; iss2 >> subs; string temp=subs; if(temp.compare("")==0) { continue; j++; } else { w[i][j]=atoi(subs.c_str()); j++; } } i++; } m=atoi( line.c_str() ); IloNumArray c(env,m); NumMatrix d(env,m); for(i=0; i<m; i++) { d[i]=IloNumArray(env,m); } i=0; j=0; getline (myfile,line); istringstream iss3(line); while (iss3 && j<m) { string subs; iss3 >> subs; string temp=subs; if(temp.compare("")==0) { continue; } else { c[j]=atoi(subs.c_str()); } j++; } i=0; j=0; while ( getline (myfile,line) && i<m) { istringstream iss4(line); j=0; while (iss4 && j<m) { string subs; iss4 >> subs; string temp=subs; if(temp.compare("")==0) { continue; } else { d[i][j]=atoi(subs.c_str()); } j++; } i++; } myfile.close(); }
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
ILOSTLBEGIN int main (int argc, char* argv[]) { //get instance fileName: const char* fileName; if(argc>1)//we passed the filename in arg fileName=argv[1]; else fileName = "instances/instances_eleves/projet_5_8_1.dat"; //DONNEES DE L INSTANCE typedef IloArray<IloNumArray> DataMatrix; IloEnv env; instance_Cplex instance ; getData(fileName,env,instance); cout << "Données récupérées!\n"; int& n(instance.n); int& m(instance.m); try { IloModel model(env); BoolVarMatrix x(env,m); for(int i=0;i<m;i++) x[i]=IloBoolVarArray(env,n); NumVarMatrix u(env,m); for(int i=0;i<m;i++) u[i]=IloNumVarArray(env,n); NumVarMatrix v(env,m); for(int i=0;i<m;i++) v[i]=IloNumVarArray(env,n); IloRangeArray constraintSet(env); IloNumVar y(env); IloNumVar z(env); cout << "Variables créées!\n"; setdata(model,env, instance, x,u,v,y,z, constraintSet); cout << " Modèle et contraintes définies!\n"; IloCplex cplex(model); cplex.solve(); IloInt solutionUnConnex; solutionUnConnex=cplex.getObjValue(); DataMatrix xUnconnex(env,m) ; //Solution optimale non connexe for(int i=0;i<m;i++){ xUnconnex[i]=IloNumArray(env,n); cplex.getValues(xUnconnex[i], x[i]); } std::string Method ="MinimizeEdges"; //connexityTree"; if(Method=="connexityTree"){ //We solve a first time the model without the connexity constraints, to get a good max bound of the height max : the value of the solution/2, then we add the connexity constraints : IloInt hMax; if(argc>2){ // we gave the hmax in argument/ istringstream (argv[2])>>hMax; if(hMax==0) hMax=solutionUnConnex/2+1; } //else we use our upper bound else hMax=solutionUnConnex/2+1;//(n*m/2+n/2); bool useCallBack=false; if(argc>3 && *argv[3]=='1') useCallBack= true; solveTreeConnexityConstraints(cplex,model,env,instance,x,u,v,y,z,useCallBack,hMax); }
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; }
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 UB, LB; switch (lattice){ case 1: // hexagonal_lattice if (max_d==3) {LB = 5; UB = 10;} //d(x) = 3 -x else {LB = 9; UB = 27;} break; case 2:// triangular_lattice if (max_d==3) { LB = 8; UB = 16;} //d(x) = 3 -x else {LB = 18; UB = 54;} break; case 3:// square_lattice if (max_d==3) { LB = 6; UB = 12;} //d(x) = 3 -x else { LB = 11; UB = 33;} break; default: UB=n*max_d;break; } std::cout << "Lattice " << lattice << "\n"; std::cout << "UB for lambda " << UB << "\n"; /* Objective*/ model.add(IloMinimize(env, lambda)); /*Constrains*/ model.add(lambda - UB <= 0); model.add(lambda - LB >= 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]; } } int M = INT_MAX;//Par_d[0][0] + UB; 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"); 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; }
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()); } IloArray<IloIntVarArray> z0(env,n); for (unsigned int i=0; i<n; i++) { std::stringstream ss; ss << i; std::string str = "z0_" + ss.str(); z0[i]= IloIntVarArray(env, n, 0, 1); } /* 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]); } */ for (unsigned u=0; u<n; u++) { for (unsigned v=0; v<u; v++) { if (Par_d[u][v] <= max_distance) { model.add(c[v]-c[u]+M*z0[u][v] >=Par_d[u][v]); model.add(c[u]-c[v]+M*(1-z0[u][v]) >=Par_d[u][v]); //Info.numvar++; } } } // d(x) = 3 - x if (max_distance == 2) { // Sechsecke mit der Seitenlaenge 1 model.add(c[0]+c[2] +c[3] +c[5] +c[6] +c[9]>=16.6077); model.add(c[1]+c[3] +c[4] +c[6] +c[7] +c[10]>=16.6077); model.add(c[5]+c[8] +c[9] +c[12]+c[13]+c[16]>=16.6077); model.add(c[6]+c[9] +c[10]+c[13]+c[14]+c[17]>=16.6077); model.add(c[7]+c[10]+c[11]+c[14]+c[15]+c[18]>=16.6077); model.add(c[13]+c[16]+c[17]+c[19]+c[20]+c[22]>=16.6077); model.add(c[14]+c[17]+c[18]+c[20]+c[21]+c[23]>=16.6077); } //d(x) = 4 - x if (max_distance == 3) { // Sechsecke mit der Seitenlaenge 1 model.add(c[0]+c[2] +c[3] +c[5] +c[6] +c[9]>=31.6077); model.add(c[1]+c[3] +c[4] +c[6] +c[7] +c[10]>=31.6077); model.add(c[5]+c[8] +c[9] +c[12]+c[13]+c[16]>=31.6077); model.add(c[6]+c[9] +c[10]+c[13]+c[14]+c[17]>=31.6077); model.add(c[7]+c[10]+c[11]+c[14]+c[15]+c[18]>=31.6077); model.add(c[13]+c[16]+c[17]+c[19]+c[20]+c[22]>=31.6077); model.add(c[14]+c[17]+c[18]+c[20]+c[21]+c[23]>=31.6077); } 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"); cplex.setParam(IloCplex::ClockType,1); 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; }
IloNum columnGeneration (IloCplex2 subSolver, IloCplex rmpSolver, IloNumVarArray3 x, IloNumVarArray2 z, IloNumVarArray2 lambda, IloObjective2 reducedCost, IloObjective rmpObj, IloRangeArray2 maintConEng, IloRangeArray2 removeMod, IloRangeArray2 convex, IloNumArray2 addXCol, IloNumArray addZCol, IloNumArray2 priceRemoveMod, IloNumArray2 priceMaintConEng, IloNumArray priceConvex, const IloNumArray2 compCosts, const IloNumArray convexityCoef, IloBool weightedDW_in, IloBool allowCustomTermination, IloInt relChangeSpan, IloNum relChange) { // extract optimization enviroment IloEnv env = rmpSolver.getEnv(); // ANALYSIS: write to file const char* output = "results/colGen_analysis.dat"; // variable declarations.. // loop counters IloInt i, m, t, testCounter; testCounter = 0; // declare two clock_t objects for start and end time. clock_t start, end; // declare an array of size NR_OF_MODULES to temporarily hold the // reduced costs from the NR_OF_MODULES different subproblems. IloNumArray redCosts(env, NR_OF_MODULES); IloBool weightedDW = weightedDW_in; // declare an array to hold the RMP objective values: e.g. add // one value to array for each iteration. // IloNumArray objValues(env); // declare an array to hold the lower bounds for the full MP, given // z(RMP)* + sum_[m in subproblems] redCost(m)^* <= z(full MP)^* <= z(RMP)^* // IloNumArray lowerBounds(env); // declare two temp IloNum objects for temporarily hold rmp objective value // and full MP lower bound. (full: MP with _all_ columns availible). IloNum tempRmpObj, tempLowerBound, bestLowerBound; bestLowerBound = -IloInfinity; // also use a num-array to hold the REL_CHANGE_SPAN most // recent RMP objective values. Used to the relative change // break criteria (if improvement by col-gen becomes to // "slow"/"flat"). IloNumArray recentObjValues(env, REL_CHANGE_SPAN); // declare and initiate col-gen iteration counter IloInt itNum = 0; // ---- weighted DW decomp - for less trailing in colgen. //IloBool weightedDW = IloTrue; // declare two IloNum-array to hold all 2x (NR_OF_MODULES x TIME_SPAN) // dual vars - or specific, best dual vars (giving highest lower bound) IloNumArray2 dualsModBest(env); IloNumArray2 dualsEngBest(env); // temp.. //IloBoolArray continueSub(env, NR_OF_MODULES); // allocate memory for sub-arrays for (m = 0; m < NR_OF_MODULES; m++) { dualsModBest.add(IloNumArray(env,TIME_SPAN)); dualsEngBest.add(IloNumArray(env,TIME_SPAN)); //continueSub[m] = IloTrue; // and maybe: initially set all dual vars to 0? for (t = 0; t < TIME_SPAN; t++) { dualsModBest[m][t] = 0.0; dualsEngBest[m][t] = 0.0; } } // also, a weight for weighted DW: IloNum weight = 2.0; // counter number of improvements of "best duals" IloInt nrOfImprov = 0; // const used in weigt IloNum weightConst = DW_WEIGHT; // initiate numarray for recent objective values // UPDATE: this is not really needed now as we check the // relative change break criteria only when we know this // vector has been filled by REL_CHANGE_SPAN "proper" values... recentObjValues[0] = 0.0; for (i = 1; i < REL_CHANGE_SPAN; i++) { recentObjValues[i] = 0.0; } // model before generation start: //rmpSolver.exportModel("rmpModel.lp"); //write results to file /* ofstream outFile(output); outFile << "Writing out results from initial column generation, T=" << TIME_SPAN << endl << "Form: [(itNum) (dual solution value) (upper bound = tempRmpObj)]" << endl << endl;*/ //cout << endl << "WE GOT OURSELVES A SEGMENTATION FAULT!" << endl; // start timer start = clock(); // also use an alternative time counter.. time_t start2, end2; start2 = time(NULL); // loop until break... for (;;) { // increase iteration counter itNum++; // solve master if ( !rmpSolver.solve() ) { env.error() << "Failed to optimize RMP." << endl; throw(-1); } // get the rmp objective value tempRmpObj = rmpSolver.getValue(rmpObj); // add to objective value array (size: iterations) // objValues.add(tempRmpObj); // update recentObjValues: recentObjValues.remove(0); // remove oldest: recentObjValues.add(tempRmpObj); // save newest // report something (... report1() ) // UPDATE: colgen is to quick for anything to see anything reported... so skip this // update weight: weight = min{ 2, if (itNum>1) { weight = (IloNum(itNum - 1) + IloNum(nrOfImprov))/2; } if ( weight > weightConst) { weight = weightConst; } // update duals // -> updates obj. functions for subproblems (w.r.t. duals) for (m = 0; m < NR_OF_MODULES; m++) { //cout << "weight = " << weight << endl; //cin.get(); for (t = 0; t < TIME_SPAN; t++) { // if we try weightedWD decomp: // for first iteration: just extract duals which will become best duals if (itNum > 1 && weightedDW) { // price associated with const. removeMod priceRemoveMod[m][t] = (rmpSolver.getDual(removeMod[m][t]))/weight + (weight-1)*(dualsModBest[m][t])/weight; // price associated with const. maintConEng priceMaintConEng[m][t] = (rmpSolver.getDual(maintConEng[m][t]))/weight + (weight-1)*(dualsEngBest[m][t])/weight; } // normally: else { // price associated with const. removeMod priceRemoveMod[m][t] = rmpSolver.getDual(removeMod[m][t]); // price associated with const. maintConEng priceMaintConEng[m][t] = rmpSolver.getDual(maintConEng[m][t]); } //cout << "priceRemoveMod[m][t] = " << priceRemoveMod[m][t] << endl; // update subproblem obj. function coefficients for z[m][t] vars: reducedCost[m].setLinearCoef(z[m][t],-(priceRemoveMod[m][t] + priceMaintConEng[m][t])); } //cin.get(); // rmpSolver.getDuals(priceRemoveMod[m], removeMod[m]); // rmpSolver.getDuals(priceMaintConEng[m], maintConEng[m]); // priceConvex[m] = -rmpSolver.getDual(convex[m][0]); // if we try weightedWD decomp: // for first iteration: just extract duals which will become best duals /* if (itNum > 1 && weightedDW) { // price associated with convexity constraint priceConvex[m] = -abs(rmpSolver.getDual(convex[m][0]))/weight - (weight-1)*(dualsConvBest[m])/weight; } */ // price associated with convexity constraint priceConvex[m] = -abs(rmpSolver.getDual(convex[m][0])); // update subproblem obj. function's constant term reducedCost[m].setConstant(priceConvex[m]); } // END of updating duals // solve subproblems for (m = 0; m < NR_OF_MODULES; m++) { //if (continueSub[m]) { // solve subproblem m cout << endl << "Solving subproblem #" << (m+1) << "." << endl; if ( !subSolver[m].solve() ) { env.error() << "Failed to optimize subproblem #" << (m+1) << "." << endl; throw(-1); } // extract reduced cost: subSolver[m].getValue(reducedCost[m]) // into a IloNumArray(env, NR_OF_MODULES) at position m. redCosts[m] = subSolver[m].getValue(reducedCost[m]); //env.out() << endl << "Reduced cost for problem #" << (m+1) << ":" << redCosts[m] << endl; // if reduced cost is negative, att optimal solution to // column pool Q(m) if (!(redCosts[m] > -RC_EPS)) { // add column addColumn(subSolver[m], x[m], z[m], lambda[m], rmpObj, maintConEng[m], removeMod[m], convex[m], addXCol, addZCol, compCosts[m], convexityCoef); //env.out() << endl << "Added a column to pool Q(" << (m+1) // << "). Lambda[" << (m+1) << "].size = " << lambda[m].getSize() << endl; testCounter++; } //else { // continueSub[m] = IloFalse; //} //} //else { // redCosts[m] = 0; //} } // END of solving subproblems (for this iteration) // calculate lower bound on full MP tempLowerBound = tempRmpObj + sumArray(redCosts); // update best lower bound if (tempLowerBound > bestLowerBound) { bestLowerBound = tempLowerBound; // increase counter for number of improved "best duals". nrOfImprov++; //cout << endl << "WHATEVAAAH" << endl; //cin.get(); // save best duals for (m = 0; m < NR_OF_MODULES; m++) { for (t = 0; t < TIME_SPAN; t++) { dualsModBest[m][t] = priceRemoveMod[m][t]; dualsEngBest[m][t] = priceMaintConEng[m][t]; } } } // update lower bounds vector //lowerBounds.add(bestLowerBound); // ANALYSIS: print out to file: // [(itNum) (dual solution value) (upper bound = tempRmpObj)] //outFile << itNum << " " << tempLowerBound << " " << tempRmpObj << endl; // if the smallest reduced cost in the updated red-cost vector // with NR_OF_MODULES entries is greater than -RC_EPS: break // otherwise, repeat. if (minMemberValue(redCosts) > -RC_EPS) { env.out() << endl << "All reduced costs non-negative: breaking." << endl; bestLowerBound = tempRmpObj; break; } // if relative change in objective value over the last REL_CHANGE_SPAN iterations is // less than REL_CHANGE, break. //if (allowCustomTermination && (itNum >= REL_CHANGE_SPAN) && (relativeImprovement(recentObjValues) < REL_CHANGE)) { if (allowCustomTermination && (itNum >= relChangeSpan) && (relativeImprovement(recentObjValues) < relChange)) { env.out() << endl << "Relative change smaller than pre-set acceptance: breaking." << endl; break; } // if the gap currentUpperBound - currentLowerBound is small enough, break if ((tempRmpObj - bestLowerBound) < RC_EPS) { env.out() << endl << "Lower<>Upper bound gap less than pre-set acceptance: breaking." << endl; cout << endl << "(tempRmpObj - bestLowerBound) = " << (tempRmpObj - bestLowerBound) << endl; bestLowerBound = tempRmpObj; break; } } // END of column generation. // alternative: print the REL_CHANGE_SPAN most recent RMP objective values env.out() << endl; /*for (i = 0; i < recentObjValues.getSize(); i++) { env.out() << "Recent #" << (i+1) << ": " << recentObjValues[i] << endl; }*/ // solve master using final column setup if ( !rmpSolver.solve() ) { env.error() << "Failed to optimize RMP." << endl; throw(-1); } // also add final objective value to objective value array (size: iterations) // objValues.add(rmpSolver.getValue(rmpObj)); // create IloNum object and extract the final RMP objective value. IloNum finalObj; finalObj = rmpSolver.getValue(rmpObj); // end program time counter(s) end = clock(); end2 = time(NULL); // print result to file //outFile << endl << endl << "Final objective value: " << finalObj << endl // << "Time required for execution: " << (double)(end-start)/CLOCKS_PER_SEC << " seconds." << endl; // outfile.close() //outFile.close(); itNum = 0; // re- use iteration counter to count total number of columns generated // nr of columns generated from each subproblem for (m = 0; m < NR_OF_MODULES; m++) { // ### outFile << "Number of columns generated from subproblem (m = " << m << "): " << (lambda[m].getSize() - 1) << endl; cout << "Number of columns generated from subproblem (m = " << m << "): " << (lambda[m].getSize() - 1) << endl; //outFile << "Pool (m = " << m << "): " << (lambda[m].getSize() - 1) << endl; itNum += lambda[m].getSize(); } // ### /* outFile << endl << "Total number of columns generated: " << itNum << endl; outFile << "Time required for column generation: " << (double)(end-start)/CLOCKS_PER_SEC << " seconds." << endl; outFile << "ALTERNATIVE: Time required for colgen: " << end2-start2 << " seconds." << endl; outFile << "RMP objective function cost: " << finalObj << endl << endl; //outFile << "Objective function values for each iteration: " << endl; //outFile << objValues; //outFile << endl << endl << "Lower bounds for each iteration: " << endl; //outFile << lowerBounds; outFile.close(); */ //cout << "Initial column generation complete, press enter to continue..." << endl; //cin.get(); // print some results.. /*env.out() << endl << "RMP objective function cost: " << finalObj << endl; env.out() << endl << "Size of objective value vector: " << objValues.getSize() << endl; env.out() << endl << "Nr of iterations: " << itNum << endl; cout << endl << "Number of new columns generated: " << testCounter << endl;*/ // Note: to explicit output (void function), ass columns are added implicitely via // income argument pointers. // clear memory assigned to temporary IloNumArrays: redCosts.end(); //objValues.end(); //lowerBounds.end(); recentObjValues.end(); // save best duals for (m = 0; m < NR_OF_MODULES; m++) { dualsModBest[m].end(); dualsEngBest[m].end(); } dualsModBest.end(); dualsEngBest.end(); //continueSub.end(); //cout << endl << "NR OF IMPROVEMENTS: " << nrOfImprov << endl; //cin.get(); // return lower bound return bestLowerBound; } // END of columnGeneration()
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 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; }
ILOBRANCHCALLBACK1(SOSbranch, IloSOS1Array, sos) { IloNumArray x; IloNumVarArray var; try { IloInt i; x = IloNumArray(getEnv()); var = IloNumVarArray(getEnv()); IloNum bestx = EPS; IloInt besti = -1; IloInt bestj = -1; IloInt num = sos.getSize(); for (i = 0; i < num; i++) { if ( getFeasibility(sos[i]) == Infeasible ) { var.clear(); sos[i].getVariables(var); getValues(x, var); IloInt n = var.getSize(); for (IloInt j = 0; j < n; j++) { IloNum inf = IloAbs(x[j] - IloRound(x[j])); if ( inf > bestx ) { bestx = inf; besti = i; bestj = j; } } } } if ( besti >= 0 ) { IloCplex::BranchDirectionArray dir; IloNumArray val; try { dir = IloCplex::BranchDirectionArray(getEnv()); val = IloNumArray(getEnv()); var.clear(); sos[besti].getVariables(var); IloInt n = var.getSize(); for (IloInt j = 0; j < n; j++) { if ( j != bestj ) { dir.add(IloCplex::BranchDown); val.add(0.0); } else { dir.add(IloCplex::BranchUp); val.add(1.0); } } makeBranch(var, val, dir, getObjValue()); makeBranch(var[bestj], 0.0, IloCplex::BranchDown, getObjValue()); } catch (...) { dir.end(); val.end(); throw; } dir.end(); val.end(); } } catch (...) { var.end(); x.end(); throw; } var.end(); x.end(); }
void kMST_ILP::solve() { try { // initialize CPLEX env = IloEnv(); model = IloModel( env ); addTreeConstraints(); // call first, initialises edges // add model-specific constraints if( model_type == "scf" ) modelSCF(); else if( model_type == "mcf" ) modelMCF(); else if( model_type == "mtz" ) modelMTZ(); else { cerr << "No existing model chosen\n"; exit( -1 ); } addObjectiveFunction(); // build model cplex = IloCplex( model ); // export model to a text file //cplex.exportModel( "model.lp" ); // set parameters setCPLEXParameters(); // solve model cout << "Calling CPLEX solve ...\n"; cplex.solve(); cout << "CPLEX finished.\n\n"; cout << "CPLEX status: " << cplex.getStatus() << "\n"; cout << "Branch-and-Bound nodes: " << cplex.getNnodes() << "\n"; cout << "Objective value: " << cplex.getObjValue() << "\n"; cout << "CPU time: " << Tools::CPUtime() << "\n\n"; // show result IloNumArray edgesSelected(env, edges.getSize()), flowRes(env, edges.getSize()), uRes(env, instance.n_nodes); cplex.getValues(edgesSelected, edges); if (model_type == "scf") { cplex.getValues(flowRes, flow_scf); } else if (model_type == "mtz") { try { cplex.getValues(uRes, u); } catch ( IloException& e ) { cerr << "Exception while extracting u: " << e << endl; uRes = IloNumArray(env, 0); } } cout << "Edges:\n"; for (unsigned int i=0; i<edges.getSize(); i++) { // skip unused ones if (((int)edgesSelected[i]) == 0 ) { continue; } if (i == instance.n_edges) { cout << endl; } bool direction = ( i >= instance.n_edges); cout << " " << setw(4) << i << ": " << ((int)edgesSelected[i]) << " "; // flow if (model_type == "scf") { cout << "f: " << setw(2) << (flowRes[i]); } else if (model_type == "mtz") { if (uRes.getSize() != 0) { cout << "u: " ; if (i < instance.n_edges) { //cout << setw(2) << instance.edges[i % instance.n_edges].v1 << ": "; cout << setw(2) <<((int)uRes[ instance.edges[i % instance.n_edges].v1]) << " "; //cout << setw(2) << instance.edges[i % instance.n_edges].v2 << ": "; cout << setw(2) << ((int)uRes[ instance.edges[i % instance.n_edges].v2]) ; } else { //cout << setw(2) << instance.edges[i % instance.n_edges].v2 << ": "; cout << setw(2) <<((int)uRes[ instance.edges[i % instance.n_edges].v2]) << " "; //cout << setw(2) << instance.edges[i % instance.n_edges].v1 << ": "; cout << setw(2) <<((int)uRes[ instance.edges[i % instance.n_edges].v1]) ; } } } cout << " " << Tools::edgeToString(instance.edges[i % instance.n_edges], direction) ; cout << endl; } } catch (IloAlgorithm::CannotExtractException& e) { cerr << "CannotExtractException: " << e << endl ; IloExtractableArray failed = e.getExtractables(); for (IloInt i = 0; i < failed.getSize(); ++i) { cerr << "\t" << failed[i] << std::endl; } } catch( IloException& e ) { cerr << "kMST_ILP: exception " << e << "\n"; exit( -1 ); } catch( ... ) { cerr << "kMST_ILP: unknown exception.\n"; exit( -1 ); } }
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; }
/***********************************************数据初始化*****************************************************/ void define_data(IloEnv env)//数据初始化,对全局变量进行赋值 { /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>变量初始化<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ for(IloInt i=0;i<Node-1;++i) { B0l[i]=IloNumArray(env,Node-1); } /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>变量初始化结束<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>数据读取<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ output<<endl<<"Unit:"<<endl; ifstream unit_information("unit_information.txt",ios::in);//常规机组分布 if(!unit_information) { output<<"no such file! unit_information.txt"<<endl; } for(IloInt i=0;i<NG;++i)//读入机组信息 { Unit[i]=IloNumArray(env,12);//12条信息:结点、Pmin、Pmax、MinOn、MinOff、RU、RD、Startup Cost、c、b、a、price; for(IloInt k=0; k<12; ++k) { unit_information>>Unit[i][k]; output<<Unit[i][k]<<" "; } output<<endl; } unit_information.close(); for(IloInt i=0;i<NG;++i) { detaa[i]=Unit[i][5]/4; } output<<endl<<"Info_Branch:"<<endl; ifstream BFile("Brach_File.txt",ios::in);//读取风电支路信息:起点,终点,电阻,电抗以及潮流上限 if(!BFile) { output<<"no such file! Brach_File.txt"<<endl; } for(IloInt k=0; k<Branch; ++k) { Info_Branch[k]=IloNumArray(env,5); for(IloInt h=0; h<5; ++h) { BFile>>Info_Branch[k][h]; output<<Info_Branch[k][h]<<" "; } output<<endl; } BFile.close(); output<<endl<<endl<<"Sw:"<<endl; ifstream wind_locate("wind_locate.txt",ios::in);//风电场分布 if(!wind_locate) { output<<"no such file! wind_locate.txt"<<endl; } for(IloInt k=0; k<Node; ++k) { wind_locate>>Sw[k]; output<<Sw[k]<<" "; if(((k+1)%20)==0) output<<endl; } output<<endl<<endl; wind_locate.close(); output<<endl<<"State and Output of Unit:"<<endl; ifstream Unit_State("Unit_State.txt",ios::in);//读取机组状态 output<<"State:"<<endl; if(!Unit_State) { output<<"no such file! Unit_State.txt"<<endl; } for(IloInt i=0; i<NG; ++i)//State { Unit_State>>u[i]; output<<u[i]<<" "; if(((i+1)%20)==0) output<<endl; } output<<endl; output<<"Output:"<<endl; for(IloInt i=0; i<NG; ++i)//Output { Unit_State>>P1[i]; output<<P1[i]<<" "; if(((i+1)%20)==0) output<<endl; } output<<endl; output<<"PL:"<<endl; for(IloInt l=0;l<Branch;++l) { Unit_State>>PL[l]; output<<PL[l]<<" "; if(((l+1)%20)==0) output<<endl; } Unit_State.close(); /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>给矩阵B0赋值<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ for(IloInt k=0; k<Node-1; ++k)//非对角线,依然以最后一个结点作为平衡结点 { B0[k]=IloNumArray(env,Node-1); for(IloInt h=0; h<Node-1; ++h) { if(k==h) continue; else { IloInt temp; IloInt b=0; for(; b<Branch; ++b) { if((Info_Branch[b][0]-1==k && Info_Branch[b][1]-1==h) || (Info_Branch[b][0]-1==h && Info_Branch[b][1]-1==k)) { temp=b; break; } } if(b==Branch) B0[k][h]=0; else B0[k][h]= -1.0/Info_Branch[temp][3]; } } } for(IloInt k=0; k<Node-1; ++k)//对角线 { B0[k][k]=0; for(IloInt h=0; h<Node-1; ++h) { if(k!=h) { B0[k][k]+=B0[k][h]; } } IloNum last=0; IloInt b=0; IloInt temp; for(;b<Branch;++b) { if((Info_Branch[b][0]-1==k && Info_Branch[b][1]-1==Node-1) || (Info_Branch[b][0]-1==Node-1 && Info_Branch[b][1]-1==k)) { temp=b; break; } } if(b==Branch) last=0; else last=-1.0/Info_Branch[temp][3]; B0[k][k]+=last; B0[k][k]=-1*B0[k][k]; } /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>给矩阵B0赋值结束<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ }
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; }
int main(int argc, char** argv) { if (argc <= 1) { cerr << "Usage: " << argv[0] << " <model>" << endl; cerr << " model = 0 -> convex piecewise linear model, " << endl; cerr << " model = 1 -> concave piecewise linear model. [default]" << endl; } IloBool convex; if (argc <= 1) convex = IloFalse; else convex = atoi(argv[1]) == 0 ? IloTrue : IloFalse; IloEnv env; try { IloInt i, j; IloModel model(env); IloInt nbDemand = 4; IloInt nbSupply = 3; IloNumArray supply(env, nbSupply, 1000.0, 850.0, 1250.0); IloNumArray demand(env, nbDemand, 900.0, 1200.0, 600.0, 400.); NumVarMatrix x(env, nbSupply); NumVarMatrix y(env, nbSupply); for(i = 0; i < nbSupply; i++) { x[i] = IloNumVarArray(env, nbDemand, 0.0, IloInfinity, ILOFLOAT); y[i] = IloNumVarArray(env, nbDemand, 0.0, IloInfinity, ILOFLOAT); } for(i = 0; i < nbSupply; i++) { // supply must meet demand model.add(IloSum(x[i]) == supply[i]); } for(j = 0; j < nbDemand; j++) { // demand must meet supply IloExpr v(env); for(i = 0; i < nbSupply; i++) v += x[i][j]; model.add(v == demand[j]); v.end(); } if (convex) { for(i = 0; i < nbSupply; i++) { for(j = 0; j < nbDemand; j++) { model.add(y[i][j] == IloPiecewiseLinear(x[i][j], IloNumArray(env, 2, 200.0, 400.0), IloNumArray(env, 3, 30.0, 80.0, 130.0), 0.0, 0.0)); } } } else { for(i = 0; i < nbSupply; i++) { for(j = 0; j < nbDemand; j++) { model.add(y[i][j] == IloPiecewiseLinear(x[i][j], IloNumArray(env, 2, 200.0, 400.0), IloNumArray(env, 3, 120.0, 80.0, 50.0), 0.0, 0.0)); } } } IloExpr obj(env); for(i = 0; i < nbSupply; i++) { obj += IloSum(y[i]); } model.add(IloMinimize(env, obj)); obj.end(); IloCplex cplex(env); cplex.extract(model); cplex.exportModel("transport.lp"); cplex.solve(); env.out() << "Solution status: " << cplex.getStatus() << endl; env.out() << " - Solution: " << endl; for(i = 0; i < nbSupply; i++) { env.out() << " " << i << ": "; for(j = 0; j < nbDemand; j++) { env.out() << cplex.getValue(x[i][j]) << "\t"; } env.out() << endl; } env.out() << " Cost = " << cplex.getObjValue() << endl; } catch (IloException& e) { cerr << "ERROR: " << e.getMessage() << endl; } catch (...) { cerr << "Error" << endl; } env.end(); return 0; } // END main