SolutionILP solveILP(const ILPModel& m, bool verbose, double gap, double timeLimit, int numberOfThreads, int)	{

    IloEnv env;
    SolutionILP solution;

    try {
        IloModel model(env);
        IloObjective obj(env);
        IloNumVarArray var(env);
        IloRangeArray con(env);
        generateProblem(m, model, var, con);

        IloCplex cplex(model);
        cplex.setParam(IloCplex::Threads, numberOfThreads);
        if (!verbose)
            cplex.setOut(env.getNullStream());
        if (gap != 0.0)
            cplex.setParam(IloCplex::EpGap, gap);
        if (timeLimit != 0.0)
            cplex.setParam(IloCplex::TiLim, timeLimit);

        cplex.solve();
        switch (cplex.getStatus())	{
        case  IloAlgorithm::Optimal:
            solution.status = ILP_OPTIMAL;
            break;
        case IloAlgorithm::Feasible:
            solution.status = ILP_FEASIBLE;
            break;
        case IloAlgorithm::Infeasible:
            solution.status = ILP_INFEASIBLE;
            break;
        case IloAlgorithm::Unbounded:
            solution.status = ILP_UNBOUNDED;
            break;
        default:
            solution.status = ILP_UNKNOWN;
        }

        if (solution.status == ILP_OPTIMAL || solution.status == ILP_FEASIBLE)	{
            IloNumArray sol(env);
            cplex.getValues(sol, var);
            solution.criterion = cplex.getObjValue();
            for (long v = 0; v < sol.getSize(); ++v)
                solution.solution.push_back(sol[v]);
        }

        solution.bound = cplex.getBestObjValue();	// Can throw IloException!
        env.end();

    } catch (IloException& e)	{
        env.end();
        throw ILPSolverException(caller(), e.getMessage());
    } catch (...) {
        env.end();
        throw_with_nested(ILPSolverException(caller(), "Error during solving the ILP problem!"));
    }

    return solution;
}
Esempio n. 2
0
int setCplexParam(IloCplex& cplex, IloEnv& env, int time_limit){
  //Set cplex parameter
  cplex.setParam(IloCplex::TiLim, time_limit);
  cplex.setParam(IloCplex::Threads, 2);
  cplex.setOut(env.getNullStream());
  cplex.setParam(IloCplex::PreLinear, 0);

  return 0;
}
Esempio n. 3
0
 void Instance::ComputeCPLEXRevenue() {
     IloEnv env;
     IloInt i, j;
     IloModel model(env);
     IloInt nbImpressions = num_impressions_;
     IloInt nbAdvertisers = num_advertisers_;
     
     NumVarMatrix x(env, nbImpressions);
     
     for(i = 0; i < nbImpressions; i++) {
         x[i] = IloNumVarArray(env, nbAdvertisers, 0.0, 1.0, ILOFLOAT);
     }
     
     // Add impression constraints.
     for(i = 0; i < nbImpressions; i++) {
         model.add(IloSum(x[i]) <= 1.0);
     }
     
     // Add weighted contraint.
     for(j = 0; j < nbAdvertisers; j++) {
         IloExpr curr_adv_constraint(env);
         for (__gnu_cxx::hash_map<int, long double>::iterator iter = bids_matrix_[j].begin();
              iter != bids_matrix_[j].end();
              ++iter) {
             curr_adv_constraint += ((double) iter->second) * ((double) weights_[j]) * x[iter->first][j];
         }
         model.add(curr_adv_constraint <= ((double) budgets_[j]));
     }
     
     IloExpr obj_exp(env);
     for(i = 0; i < nbImpressions; i++) {
         for(j = 0; j < nbAdvertisers; j++) {
             obj_exp += ((double) transpose_bids_matrix_[i][j]) * x[i][j];
         }
     }
     
     model.add(IloMaximize(env, obj_exp));
     obj_exp.end();
     
     IloCplex cplex(env);
     cplex.setOut(env.getNullStream());
     cplex.extract(model);
     
     // Optimize the problem and obtain solution.
     if ( !cplex.solve() ) {
         env.error() << "Failed to optimize LP" << endl;
         throw(-1);
     }
     
     cplex.exportModel("/Users/ciocan/Documents/Google/data/example.lp");
     
     cout << "CPLEX opt is " << cplex.getObjValue() << "\n";
     
     env.end();    
 }
Esempio n. 4
0
int
main (int argc, char **argv)
{
   IloEnv env;
   try {
      IloModel model(env, "example");

      IloNumVarArray var(env);
      IloRangeArray  rng(env);
      populatebycolumn (model, var, rng);

      IloCplex cplex(model);
      cplex.setOut(env.getNullStream());
      cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Primal);
      cplex.use(MyCallback(env));
      cplex.solve();

      env.out() << "Solution status = " << cplex.getStatus() << endl;
      env.out() << "Solution value  = " << cplex.getObjValue() << endl;

      IloNumArray vals(env);
      cplex.getValues(vals, var);
      env.out() << "Values        = " << vals << endl;
      cplex.getSlacks(vals, rng);
      env.out() << "Slacks        = " << vals << endl;
      cplex.getDuals(vals, rng);
      env.out() << "Duals         = " << vals << endl;
      cplex.getReducedCosts(vals, var);
      env.out() << "Reduced Costs = " << vals << endl;

      cplex.exportModel("lpex4.lp");
   }
   catch (IloException& e) {
      cerr << "Concert exception caught: " << e << endl;
   }
   catch (...) {
      cerr << "Unknown exception caught" << endl;
   }

   env.end();
   return 0;
}  // END main
Esempio n. 5
0
void profit_solve(graph g, vector<int>& allocation, vector<double>& pricing, bool integer) {
  int **columns = (int **)malloc(g->bidders * sizeof(int *));
  for(int i = 0; i < g->bidders; i++)
    columns[i] = (int *)calloc(g->items, sizeof(int));
  IloEnv env;
  try {
    if(getVerbosity() != CplexOutput)
      env.setOut(env.getNullStream());
    IloModel model(env);
    IloNumVarArray x(env);
    IloNumVarArray p(env);
    IloNumVarArray z(env);
    IloCplex cplex(model);
    profit_create_vars(g, model, x, p, z, columns);
    profit_create_objective(g, model, x, z, columns);
    model.add(profit_constraints(g, model, x, p, z, columns));
    config_cplex(cplex); 
    if(!integer) {
      model.add(IloConversion(env, x, ILOFLOAT));
    } else {
      profit_load(g, cplex, model, x, p, z, columns, allocation, pricing);
    }
    clock_start();
    if (!cplex.solve()) {
      failed_print(g);
    } else {
      if(integer)
        solution_print(cplex, env, g);  
      else
        relax_print(cplex, env);
    }
  }
  catch (IloException& e) {
    cerr << "Concert exception caught: " << e << endl;
  }
  catch (...) {
    cerr << "Unknown exception caught" << endl;
  }
}
Esempio n. 6
0
// This routine set up the IloCplex algorithm to solve the worker LP, and
// creates the worker LP (i.e., the dual of flow constraints and
// capacity constraints of the flow MILP)
//
// Modeling variables:
// forall k in V0, i in V:
//    u(k,i) = dual variable associated with flow constraint (k,i)
//
// forall k in V0, forall (i,j) in A:
//    v(k,i,j) = dual variable associated with capacity constraint (k,i,j)
//
// Objective:
// minimize sum(k in V0) sum((i,j) in A) x(i,j) * v(k,i,j)
//          - sum(k in V0) u(k,0) + sum(k in V0) u(k,k)
//
// Constraints:
// forall k in V0, forall (i,j) in A: u(k,i) - u(k,j) <= v(k,i,j)
//
// Nonnegativity on variables v(k,i,j)
// forall k in V0, forall (i,j) in A: v(k,i,j) >= 0
//
void
createWorkerLP(IloCplex cplex, IloNumVarArray v, IloNumVarArray u, 
               IloObjective obj, IloInt numNodes)
{

   IloInt i, j, k;
   IloEnv env = cplex.getEnv();
   IloModel mod(env, "atsp_worker"); 

   // Set up IloCplex algorithm to solve the worker LP

   cplex.extract(mod);
   cplex.setOut(env.getNullStream());
      
   // Turn off the presolve reductions and set the CPLEX optimizer
   // to solve the worker LP with primal simplex method.

   cplex.setParam(IloCplex::Reduce, 0);
   cplex.setParam(IloCplex::RootAlg, IloCplex::Primal); 
   
   // Create variables v(k,i,j) forall k in V0, (i,j) in A
   // For simplicity, also dummy variables v(k,i,i) are created.
   // Those variables are fixed to 0 and do not partecipate to 
   // the constraints.

   IloInt numArcs  = numNodes * numNodes;
   IloInt vNumVars = (numNodes-1) * numArcs;
   IloNumVarArray vTemp(env, vNumVars, 0, IloInfinity);
   for (k = 1; k < numNodes; ++k) {
      for (i = 0; i < numNodes; ++i) {
         vTemp[(k-1)*numArcs + i *numNodes + i].setBounds(0, 0);
      }
   }
   v.clear();
   v.add(vTemp);
   vTemp.end();
   mod.add(v);

   // Set names for variables v(k,i,j) 

   for (k = 1; k < numNodes; ++k) {
      for(i = 0; i < numNodes; ++i) {
         for(j = 0; j < numNodes; ++j) {
            char varName[100];
            sprintf(varName, "v.%d.%d.%d", (int) k, (int) i, (int) j); 
            v[(k-1)*numArcs + i*numNodes + j].setName(varName);
         }
      }
   }
   
   // Associate indices to variables v(k,i,j)

   IloIntArray vIndex(env, vNumVars);
   for (j = 0; j < vNumVars; ++j)
   {
      vIndex[j] = j;
      v[j].setObject(&vIndex[j]);
   }

   // Create variables u(k,i) forall k in V0, i in V

   IloInt uNumVars = (numNodes-1) * numNodes;
   IloNumVarArray uTemp(env, uNumVars, -IloInfinity, IloInfinity);
   u.clear();
   u.add(uTemp);
   uTemp.end();
   mod.add(u);

   // Set names for variables u(k,i) 

   for (k = 1; k < numNodes; ++k) {
      for(i = 0; i < numNodes; ++i) {
         char varName[100];
         sprintf(varName, "u.%d.%d", (int) k, (int) i); 
         u[(k-1)*numNodes + i].setName(varName);
      }
   }

   // Associate indices to variables u(k,i)

   IloIntArray uIndex(env, uNumVars);
   for (j = 0; j < uNumVars; ++j)
   {
      uIndex[j] = vNumVars + j;
      u[j].setObject(&uIndex[j]);
   }

   // Initial objective function is empty

   obj.setSense(IloObjective::Minimize);
   mod.add(obj);

   // Add constraints:
   // forall k in V0, forall (i,j) in A: u(k,i) - u(k,j) <= v(k,i,j)

   for (k = 1; k < numNodes; ++k) {
      for(i = 0; i < numNodes; ++i) {
         for(j = 0; j < numNodes; ++j) {
            if ( i != j ) {
               IloExpr expr(env);
               expr -= v[(k-1)*numArcs + i*(numNodes) + j];
               expr += u[(k-1)*numNodes + i];
               expr -= u[(k-1)*numNodes + j];
               mod.add(expr <= 0);
               expr.end();
            }
         }
      }
   }

}// END createWorkerLP
Esempio n. 7
0
void solveLP(){
	IloEnv env;
	IloModel model(env);
	IloNumVarArray x(env, n_var, 0,1);
	IloRangeArray con(env);
	IloExpr obj(env);
	int i,j,k;
	for(i=0;i<n;i++){
		for(j=0;j<group[i].nItem;j++){
			obj+=group[i].profit[j]*x[sum_n_item[i]+j];
		}
	}
	model.add(IloMaximize(env,obj));
	obj.end();
	for(k=0;k<m;k++){
		IloExpr expr(env);
		for(i=0;i<n;i++){
			for(j=0;j<group[i].nItem;j++){
				expr+=group[i].consume[j][k]*x[sum_n_item[i]+j];
			}
		}
		con.add(expr<=Gb[k]);
		expr.end();
	}
	for(i=0;i<n;i++){
		IloExpr expr(env);
		for(j=0;j<group[i].nItem;j++){
			expr+=x[sum_n_item[i]+j];
		}
		con.add(expr==1);
		expr.end();
	}
	
	model.add(con);
	IloCplex cplex(model);
	cplex.setOut(env.getNullStream());
	cplex.setParam(IloCplex::Threads,1);
	if(cplex.solve()){
		printf("LP solved with new value: %lf \n\n", cplex.getObjValue());
		UB=cplex.getObjValue();
		len_rdCost0=len_rdCost1=0;
		for(i=0;i<n_var;i++) {
			primal_sol[i]=(double)cplex.getValue(x[i]);
			rdCosts[i]=FABS((double)cplex.getReducedCost(x[i]));
			if(primal_sol[i]<EPSILON && rdCosts[i]>EPSILON){// non-basic variables at 0
				rdCost_sort[len_rdCost0].value=rdCosts[i];
				rdCost_sort[len_rdCost0++].posi=i;
			} else if(primal_sol[i]>1-EPSILON && rdCosts[i]>EPSILON){// non-basic variables at 1
				rdCost_sort1[len_rdCost1].value=rdCosts[i];
				rdCost_sort1[len_rdCost1++].posi=i;
			}
		}
		qsort(rdCost_sort, len_rdCost0,sizeof(ValuePosi), cmp);
		qsort(rdCost_sort1, len_rdCost1, sizeof(ValuePosi), cmp);
		
		len_v1=new int[maxIte];
		len_v0=new int[maxIte];

		pre_v0=new int*[maxIte];
		pre_v1=new int*[maxIte];
		for(i=0;i<maxIte;i++){
			pre_v1[i]=new int[len_rdCost1];
			pre_v0[i]=new int[len_rdCost0];
		}
		sum_pre_v1=new int[maxIte];
		memset(len_v0, 0,maxIte*sizeof(int));
		memset(len_v1, 0, maxIte*sizeof(int));
		memset(sum_pre_v1, 0, maxIte*sizeof(int));
	} else{ 
		printf("LP not solved\n");
	}
}
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;
}
Esempio n. 9
0
int solve_LP()
{
   //--------基本环境设置--------
   IloEnv env; //环境environment
   IloModel model(env); //model
   int i,s,j,k;

   //-------常量变量设置--------
   IloNumArray a1 (env, num_i); //[1,1,...,1]
   for(i=0;i<num_i;i++)
	   a1[i] = 1;

   IloIntArray m (env,num_s); //VM allocation
   for(s=0;s<num_s;s++)
	   m[s] = y[s];

   /*cout<<"VM: ";
   for(s=0;s<num_s;s++)
	   cout<<m[s]<<" ";
   cout<<endl;*/

   //-------待定变量设置------
   NumVarCubic f(env, num_s); //f[s][j][i], f[4][4][2]
   for(s=0;s<num_s;s++)
   {
	   f[s] = NumVarMatrix(env,num_s);
	   for(j=0;j<num_s;j++)
		   f[s][j] = IloNumVarArray(env, num_i, 0, 1 );
   }

   NumVarCubic x(env, num_i); //x[i][s][j], x[2][4][4]
   for(i=0;i<num_i;i++)
   {
	   x[i] = NumVarMatrix(env,num_s);  
	   for(s=0;s<num_s;s++)
		   x[i][s] = IloNumVarArray(env, num_s, 0, IloInfinity );
   }

   IloNumVar bottleneck (env);
   
   //----优化目标----
   model.add(IloMinimize(env,bottleneck));

   //----------cplex列方程---------
   //--bottleneck--
   for(i=0;i<num_i;i++)
	   for(s=0;s<num_s;s++)
		   model.add(  B* IloScalProd( m, x[i][s]) /link[i][s] <= bottleneck);

   //--f--
   for(i=0;i<num_i;i++)  //f[i][s][s] =0
	   for(s=0;s<num_s;s++)
		   model.add( f[s][s][i] == 0);

   for(i=0;i<num_i;i++)  //f[i][j][k] = f[i][k][j]
	   for(j=0;j<num_s;j++)
		   for(k=j+1;k<num_s;k++)
			   model.add( f[j][k][i] - f[k][j][i] == 0 );

   for(j=0;j<num_s;j++)  //比例和为一
	   for(k=j+1;k<num_s;k++)
		   model.add(  IloScalProd( a1,f[j][k] ) == 1);

   //--x--
   /*for(i=0;i<num_i;i++)
	   for(s=0;s<num_s;s++)
		   model.add(  B* IloScalProd( m, x[i][s]) <= link[i][s]);*/
   model.add( bottleneck <= 1);

	for(i=0;i<num_i;i++)
	   for(s=0;s<num_s;s++)
		   for(j=0;j<num_s;j++)
		   {
			   if(j==s)
				   continue;
			   model.add( x[i][s][s] + x[i][s][j] - f[s][j][i] >= 0 );
		   }
	
	//---------Cplex解方程---------	   
	IloCplex cplex(model); //依model建的cplex
	cplex.setOut(env.getNullStream());

	double tar;
	if(cplex.solve())
	{
		tar = cplex.getObjValue();
		if(tar<bn_best) 
			bn_best = tar; 
		env.end();
		return 1;
	}
	
	else
	{
		//cout<<"No Solution!\n\n";
		env.end();
		return 0;
	}
}
Esempio n. 10
0
bool LpSolver::solveLpProblem(CplexConverter& cplexConverter, string mode)
{
	// clock_t t;
	// t = clock();
	
	IloEnv   env;
	bool success = false;
	try {
		IloModel model(env);
		IloNumVarArray var(env);
		IloRangeArray con(env);
		this->populatebyrow(cplexConverter, model, var, con); //modify where the graph is located
		this->addObjective(mode, cplexConverter, model, var, con);
		IloCplex cplex(model);

		// cout << "before solving " << endl;
		// cout << var << endl;
		// cout << con << endl;

		cplex.setOut(env.getNullStream());
		// Optimize the problem and obtain solution.
		if ( !cplex.solve() ) {
		   // env.error() << "Failed to optimize LP" << endl;
		   throw(-1);
		}

		IloNumArray vals(env);
		
		// env.out() << "Solution status = " << cplex.getStatus() << endl;
		// env.out() << "Solution value  = " << cplex.getObjValue() << endl;
		// cplex.getValues(vals, var);
		// env.out() << "Values        = " << vals << endl;
		// cplex.getSlacks(vals, con);
		// env.out() << "Slacks        = " << vals << endl;
		// cplex.getDuals(vals, con);
		// env.out() << "Duals         = " << vals << endl;
		// cplex.getReducedCosts(vals, var);
		// env.out() << "Reduced Costs = " << vals << endl;
		
    	// cplex.exportModel("lpex1.lp");

		for (int i = 0; i < cplexConverter.variables.size(); ++i){
			cout << "results from LP: " << cplex.getValue(var[i]) << endl;
			cplexConverter.results.push_back(cplex.getValue(var[i]));
		}

		// cout << "after solving " << endl;
		// cout << var << endl;
		// cout << con << endl;
		success = true;

	}
	catch (IloException& e) {
		// cerr << "Concert exception caught: " << e << endl;
	}
	catch (...) {
		// cerr << "Unknown exception caught" << endl;
	}
	env.end();


	// t = clock() - t;
	// printf ("It took me %d clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);

	return success;
}
Esempio n. 11
0
ScenarioResult * ScenarioProblem::simProblem(){
	ScenarioResult * sr = new ScenarioResult(_pd);
	
	int seed = _pd->getSeed() + _scenario*100000 + _trial*33000;
	int subSeed;

	if(!_pd->getSubProblemGenerated()){
	  _simSP.generateSubProblem(0,_pd,_scenario);
	}

	//	IloEnv env;
	//	_pd->setEnv(env);

	IloEnv env = _pd->getEnv();
	IloModel mod(env);
	addSimProblem(mod);

 try
  {
    IloCplex cplex(mod);
 
	
	
	cplex.setOut(env.getNullStream());

	Tree<Node> ref;
	ref.buildTree( _pd->getOutcomes(), _pd->getStages());



	Grid* g = _pd->getGrid();
	int E = _pd->getGrid()->getBranchSize();
	int V = _pd->getGrid()->getBusSize();
	
	
	IloNum temp;
	IloNumArray tempA(env);
	IloNumArray tempB(env);
	double R;
	double L = _pd->getEffectiveDistribution();
	double U;
	double f;
	double fabs;
	double alpha;
	double x;
	int parent;
	double tempCount;
	int isDone;

	//fix x variables
	for(int j=0;j<E; j++){
		_simSP.setOutage(j, false);
	}

	//add outages
	for(int j=0; j<_pd->getNumberOutages(_scenario) ; j++){
	  _simSP.setOutage(_pd->getOutages(_scenario,j), true);
	}

	for(int i=0;i<ref.getSize();i++){
		subSeed = seed + i*1000;
		parent= ref[i]->getParent();
		
		if( i!= 0 && _pd->getEnergyStorage() ){//storage logic
			//cout<<"\ni:"<<i<<",pnt:"<<parent<<",es:"<<sr->getETotal(parent);
			for(int j=0; j<V; j++){
				_simSP.setPriorES(j, sr->getE( parent, j ) );
			}
			
		}

		if( i!=0 )	isDone = (int)sr->getDone( parent );
		else		isDone = 0;

		if( isDone ){
			sr->updateDone(i, 1);

			sr->updateDTotal(i,sr->getDTotal(parent));
			sr->updatePDeltaTotal(i,0);
			sr->updateXTotal(i,sr->getXTotal(parent));
		}
		else{
			tempCount=0;
			for(int j=0; j<E; j++){		//set branch outages
			
				if( i!=0) {	
					//OUTAGE LOGIC if not root node
					x = sr->getX(parent,j);
					if( x == 0 ){	//branch not out
						srand(subSeed + j);
						alpha = rand() / double(RAND_MAX);  //uniform 0-1
						U = g->getBranchCapacity(j);
						R = L + (1-L)*alpha;
						R = R*U;
						
					
						alpha = rand() / double(RAND_MAX);  //uniform 0-1
						if (  alpha > _pd->getProbability() ) R = U + 1;
						
						
						f = sr->getF(parent,j); 
						if( f > 0 )  fabs = f;
						else fabs = -f;

						//outage branches
						if( fabs > R) {
							_simSP.setOutage(j,true);
							tempCount += 1;
						}
						else		_simSP.setOutage(j,false);
					}
					else{
						_simSP.setOutage(j,true);
					}
				
				}
			}
			if(tempCount>0)	sr->updateDone(i,0);
			else if(tempCount==0 && i != 0)	sr->updateDone(i,1);
			else sr->updateDone(i,0);

		if(cplex.solve()){
			
//			temp = 	cplex.getObjValue();
			temp = cplex.getValue( _simSP.getSumD() );
			sr->updateDTotal(i,temp);

			cplex.getValues(tempA, _simSP.getD() );
			tempCount=0;
			for(int j=0; j<V; j++){
			  sr->updateD(i, j,tempA[j]);	//bus injects
			}

			cplex.getValues(tempA, _simSP.getP() );
			tempCount=0;
			for(int j=0; j<V; j++){
			  sr->updateP(i, j,tempA[j]);	//bus injects
				if( i!=0 ){
					temp = tempA[j];
					temp -= sr->getP( parent, j);
					sr->updatePDelta(i,j,temp);
					if(temp < 0) tempCount -= 0;//temp;
					else tempCount += temp;
				}
			}
			sr->updatePDeltaTotal(i,tempCount);
			
			cplex.getValues(tempA, _simSP.getF() );
			for(int j=0; j<E; j++){
			  sr->updateF(i,j, tempA[j]);	//branch flows
			}
			cplex.getValues(tempA, _simSP.getX() );
			tempCount=0;
			for(int j=0; j<E; j++){
			  sr->updateX(i,j, tempA[j]);	//branch flows
				tempCount+= tempA[j];
			}
			sr->updateXTotal(i,tempCount);

			if(_pd->getEnergyStorage() ){
				cplex.getValues(tempA, _simSP.getE() );
				for(int j=0; j<V; j++){
				  sr->updateE(i,j, tempA[j]);	//branch flows
				}
				temp = cplex.getValue( IloSum(_simSP.getEDeltaPlus() ) );
				sr->updateEDeltaPlus(i, temp);
				temp = cplex.getValue( IloSum(_simSP.getEDeltaMinus() ) );
				sr->updateEDeltaMinus(i, temp);
				temp = cplex.getValue( IloSum(_simSP.getE() ) );
				sr->updateETotal(i, temp);
			}
		}
		}
	}
	//	mod.end();
	//	env.end();

 }
  catch (IloException e)
  {
    cout << "An exception occurred. Exception Nr. " << e << endl;
  }

	return sr;
}
Esempio n. 12
0
ILOSTLBEGIN

int main(int argc, char **argv) 
{
	IloEnv env;	
	try 
	{
		
		IloArray<IloNumArray> distance(env);
		
		//Model Initialization
		IloModel model(env);

		//Taking Data from Distance Data File
		ifstream in;
		in.open("carpool-data.txt",ios::in);
		in >> distance;
		in.close();
		cout<<distance<<endl;
		
		//2D Array for Results
		IloArray<IloNumArray> X_val(env, 7);
		for (int i = 0; i < 7; i++)
		{
			X_val[i] = IloNumArray(env,7);
		}

		IloArray<IloNumArray> Y_val(env, 7);
		for (int i = 0; i < 7; i++)
		{
			Y_val[i] = IloNumArray(env,7);
		}

		//2D Array for Xij
		IloArray<IloNumVarArray> X(env, 7);
		for (int i = 0; i < 7; i++)
		{
			X[i] = IloNumVarArray(env,7,0,1,ILOINT);
		}

		//2D Array for Yij
		IloArray<IloNumVarArray> Y(env, 7);
		for (int i = 0; i < 7; i++)
		{
			Y[i] = IloNumVarArray(env,7,0,1,ILOINT);
		}

		// 1D array for Ui and U-val
		//IloNumVarArray U(env,7,0,7,ILOINT);
		//IloNumArray U_val(env,7);

		// Defining Obj to be equal to sum-product(Dij*Xij + Dij*Yij)
 		IloExpr Obj(env);
 		for (int i = 0; i < 7; ++i)
 		{
 			for (int j = 0; j < 7; j++)
 			{
				if(i != j)
				{
 				Obj += distance[i][j]*X[i][j] + distance[i][j]*Y[i][j];
				}
 			}
 		}
		
		//model.add(IloMaximize(env,Obj)); // IloMinimize is used for minimization problems
		//Alternatively, model.add(IloMaximize(env,Obj)); can be replaced by the following three lines.
		//This is useful while iterating in Decomposition Techniques where the objective function is redefined at each iteration
		IloObjective Objective = IloMinimize(env); 
		model.add(Objective); 
		Objective.setExpr(Obj);
		Obj.end();

		//Constraints for the model

		//One Input per Node except Office
		IloExpr Input(env);
		for (int i = 0; i < 6; i++)
		{
			for (int j = 0; j < 7; j++)
			{
				if(i != j )
				{
				Input += X[i][j] + Y[i][j];
				}
			}
			model.add(Input == 1);
		}
		Input.end();
		
		//One Output per Node except Office
		IloExpr Output(env);
		for (int j = 0; j < 6; j++)
		{
			for (int i = 0; i < 7; i++)
			{
				if(i != j )
				{
				Output += X[i][j] + Y[i][j];
				}
			}
			model.add(Output == 1);
		}
		Output.end();
	
		//Ensuring 2 entries and exits for the Office node
		IloExpr Entryx(env);
		for (int i = 0; i <6; i++)
		{
			Entryx = Entryx + X[i][6];		
		}
		model.add(Entryx == 1);
		Entryx.end();

		IloExpr Exitx(env);
		for (int i = 0; i <6; i++)
		{
			Exitx = Exitx + X[6][i];
		}
		model.add(Exitx == 1);
		Exitx.end();

		IloExpr Entryy(env);
		for (int i = 0; i <6; i++)
		{
			Entryy = Entryy + Y[i][6];		
		}
		model.add(Entryy == 1);
		Entryy.end();

		IloExpr Exity(env);
		for (int i = 0; i <6; i++)
		{
			Exity = Exity + Y[6][i];
		}
		model.add(Exity == 1);
		Exity.end();

		// Optimize
		IloCplex cplex(model);
		cplex.setOut(env.getNullStream()); // if we get an empty stream in return
		//cplex.setWarning(env.getNullStream());
		cplex.solve();//solving the MODEL
		//cout << "hey there I reached the breakpoint" << endl;
		if (cplex.getStatus() == IloAlgorithm::Infeasible) // if the problem is infeasible
		{
			env.out() << "Problem Infeasible" << endl; 
		}
		for(int i = 0; i < 7 ; i++)
		{
			cplex.getValues(X_val[i], X[i]);
		}
		cout<<X_val<<endl;
		for(int i = 0; i < 7 ; i++)
		{
			cplex.getValues(Y_val[i], Y[i]);
		}
		cout<<Y_val<<endl;
		//	cplex.getValues(U_val,U);
		// Print results
		cout<< "Objective Value = " << cplex.getObjValue() << endl;
		//cout<<"X = "<<X_val<<endl;
	}
	catch(IloException &e) 
	{
		env.out() << "ERROR: " << e << endl;
	}
	catch(...)
	{
		env.out() << "Unknown exception" << endl;
	}
	env.end();
	return 0;
}
Esempio n. 13
0
 void Instance::VerifySolution() {
     IloEnv env;
     IloInt i, j;
     IloModel model(env);
     IloInt nbImpressions = num_impressions_;
     IloInt nbAdvertisers = num_advertisers_;
     
     NumVarMatrix x(env, nbImpressions);
     // NumVarMatrix y(env, nbImpressions);
     
     for(i = 0; i < nbImpressions; i++) {
         x[i] = IloNumVarArray(env, nbAdvertisers, 0.0, 1.0, ILOFLOAT);
         // y[i] = IloNumVarArray(env, nbAdvertisers, 0.0, 1.0, ILOFLOAT);
     }
     
     // Add impression constraints.
     for(i = 0; i < nbImpressions; i++) {
         model.add(IloSum(x[i]) <= 1.0);
     }
     
     // Add weighted contraint.
     IloExpr weighted_constraint(env);
     for(j = 0; j < nbImpressions; j++) {      // demand must meet supply
         for(i = 0; i < nbAdvertisers; i++) {
             weighted_constraint += ((double) transpose_bids_matrix_[j][i]) * ((double) weights_[i]) * x[j][i];
         }
     }
     model.add(weighted_constraint <= ((double) global_problem_.budget_));
     weighted_constraint.end();
     
     IloExpr obj_exp(env);
     for(i = 0; i < nbImpressions; i++) {
         for(j = 0; j < nbAdvertisers; j++) {
             obj_exp += ((double) transpose_bids_matrix_[i][j]) * x[i][j];
         }
     }
     
     model.add(IloMaximize(env, obj_exp));
     obj_exp.end();
 
     IloCplex cplex(env);
     cplex.setOut(env.getNullStream());
     cplex.extract(model);
     
     // Optimize the problem and obtain solution.
     if ( !cplex.solve() ) {
         env.error() << "Failed to optimize LP" << endl;
         throw(-1);
     }
     
     IloNumArray vals(env);
     
     long double sum_b = 0;
     for (int a = 0; a < num_advertisers_; ++a) {
         //slacks_[a] = 0;
         for (i = 0; i < nbImpressions; i++) {
             if (cplex.getValue(x[i][a]) > 0) {
                 //slacks_[a] = slacks_[a] + cplex.getValue(x[i][a]) * bids_matrix_[a].find(i)->second;
                 sum_b += cplex.getValue(x[i][a]) * bids_matrix_[a].find(i)->second * weights_[a];
             }
         }
     }
     
     cout << "Cplex buget allocation is = ";
     cout << sum_b;
     cout << "\n";
     
     if (cplex.getObjValue() == CalculateGlobalMWProblemOpt()) {
         cout << "Solution checks \n";
     } else {
         cout << "Solution does not check, Cplex opt is ";
         cout << cplex.getObjValue();
         cout << "\n";
     }
     env.end();
 }
Esempio n. 14
0
   /** Create a new worker.
    * The constructor mainly does the following:
    * - create an IloCplex instance that refers to a remote worker,
    * - load the model in <code>modelfile</code>,
    * - setup parameters depending on this worker's index,
    * - start an asynchronous solve.
    * If anything fails then an exception will be thrown.
    * @param env The environment used for instantiating Ilo* objects.
    * @param i The index of the worker to be created. This also
    *          determines the parameter settings to use in this worker.
    * @param s  A pointer to the global solve state.
    * @param transport  The transport name for the IloCplex constructor.
    * @param argc       The argument count for the IloCplex constructor.
    * @param argv       The array of transport arguments for the IloCplex
    *                   constructor.
    * @param modelfile  Name of the model to be loaded into the worker.
    * @param output     The output mode.
    * @param objdiff    The minimal difference between so that two
    *                   consecutive objective function values are considered
    *                   different.
    */
   Worker(IloEnv env, int i, SolveState *s, char const *transport,
          int argc, char const **argv, char const *modelfile,
          OUTPUT output, double objdiff)
      : idx(i), state(s), model(env), cplex(0), handle(0),
        primal(IloInfinity), dual(-IloInfinity),
        obj(env), x(env), rng(env), infoHandler(this), outb(idx), outs(&outb)
   {
      try {
         // Create remote object, setup output and load the model.
         cplex = IloCplex(model, transport, argc, argv);
         switch (output) {
         case OUTPUT_SILENT:
            // Disable output on the output and warning stream.
            cplex.setOut(env.getNullStream());
            cplex.setWarning(env.getNullStream());
            break;
         case OUTPUT_PREFIXED:
            // Redirect output to our custom stream.
            cplex.setOut(outs);
            cplex.setWarning(outs);
            break;
         case OUTPUT_LOG:
            // Nothing to do here. By default output is enabled.
            break;
         }
         cplex.importModel(model, modelfile, obj, x, rng);
         if ( obj.getSense() == IloObjective::Minimize ) {
            primal = -IloInfinity;
            dual = IloInfinity;
         }

         // We set the thread count for each solver to 1 so that we do not
         // run into problems if multiple solves are performed on the same
         // machine.
         cplex.setParam(IloCplex::Param::Threads, 1);
         // Each worker runs with a different random seed. This way we
         // get different paths through the tree even if the other
         // parameter settings are the same.
         cplex.setParam(IloCplex::Param::RandomSeed, idx);
         // Apply parameter settings.
         for (class ParamValue const *vals = settings[idx % NUMSETTINGS].values;
              vals->isValid(); ++vals)
            vals->apply(cplex);

         // Install callback and set objective change.
         int status = cplex.userfunction (USERACTION_ADDCALLBACK,
                                          0, NULL, 0, 0, NULL);
         if ( status )
            throw status;
         IloCplex::Serializer s;
         s.add(objdiff);
         status = cplex.userfunction (USERACTION_CHANGEOBJDIFF,
                                      s.getRawLength(), s.getRawData(),
                                      0, 0, NULL);
         if ( status )
            throw status;

         // Register the handler that will process info messages sent
         // from the worker.
         cplex.setRemoteInfoHandler(&infoHandler);

         // Everything is setup. Launch the asynchronous solve.
         handle = cplex.solve(true);
      } catch (...) {
         // In case of an exception we need to take some special
         // cleanup actions. Note that if we get here then the
         // solve cannot have been started and we don't need to
         // kill or join the asynchronous solve.
         if ( cplex.getImpl() )
            cplex.end();
         rng.end();
         x.end();
         obj.end();
         model.end();
         throw;
      }
   }
Esempio n. 15
0
int timeModel<type,type2>::Solve(const Problem<type>& P,Solution<type,type2> &s,double time_limit,int ERIneq) {
  try{
    IloNum start,time_exec;
    const int n= P.nbTask;
    IloInt cptCut=0;
  
    IloEnv env;
    IloModel model(env);
  		
    IloNumVarMatrix x(env,n);
    IloNumVarMatrix y(env,n);
    IloNumVarMatrix b(env,n);
    IloNumVarMatrix w(env,n);

    createModel(P,env,model,x,y,b,w);
    IloCplex cplex(model);

    if (ERIneq==1) {
      std::cout << " Starting resolution with ER inequalities at root node\n";
      addERinequalities(P,env,model,x,y);
    }
  
    if (ERIneq==2) {
      std::cout << " Starting resolution with ER inequalities in tree <10\n";
      IloInt nodeDepth=0;
      IloInt maxDepth=10;
      cplex.use(depth(env,nodeDepth));
      cplex.use(energyCuts(env,P,x,y, 0.01, cptCut,nodeDepth,maxDepth));
    }
    else 
      std::cout << " Starting resolution without ER inequalities\n";
				
    cplex.setParam(IloCplex::TiLim, time_limit);
    cplex.setParam(IloCplex::Threads,2);
    cplex.setOut(env.getNullStream());
    start= cplex.getCplexTime();
    IloInt cpt=0;
    cplex.use(getFirstSolInfo(env,cpt,start));
    // solve !
    if (cplex.solve()) {	 
      time_exec=cplex.getCplexTime()-start;
      std::cout << "Final status: \t"<< cplex.getStatus() << " en " 
		<< time_exec << std::endl;
      std:: cout << "Final objective: " << cplex.getObjValue() 
		 <<"\nFinal gap: \t" << cplex.getMIPRelativeGap()
		 << std::endl;   
      if (ERIneq==2) 
	std::cout << "number of preemp cuts: "
		  << cptCut << "\n";
      modelToSol(P,s,cplex,x,y,b);
      env.end();
      return 0;
    }
    else if (cplex.getStatus()==IloAlgorithm::Infeasible){
      time_exec=cplex.getCplexTime()-start;
      if (ERIneq==2) std::cout << "number of ER cuts: "
			       << cptCut << "\n";
      std::cout << "status: "<< cplex.getStatus() << " en " 
		<< time_exec << std::endl;
    }
    env.end();
    return 1;
  }
  catch (IloException &e) {
    std::cout << "Iloexception in solve" << e << std::endl;
    e.end();
    return 1;
  } 
  catch (...){
    std::cout << "Error unknown\n";
    return 1;
  }
}
Esempio n. 16
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;
}
Esempio n. 17
0
int compute_evc_bound_using_sukp(Dataset &dataset,
		const std::unordered_set<const std::set<int>*> &collection, const
		stats_config &stats_conf, std::pair<int,int> &result) {
	std::ifstream dataset_s(dataset.get_path());
	if(! dataset_s.good()) {
		std::cerr << "ERROR: cannot open dataset file" << std::endl;
		dataset_s.close();
		std::exit(EXIT_FAILURE);
	}
	if (collection.empty()) {
		result.first = 0;
		result.second = 0;
		return 1;
	}
	// The following is called U in the pseudocode
	std::unordered_set<int> items;
	int collection_size = 0;
	for (const std::set<int> *itemset : collection) {
		items.insert(itemset->begin(), itemset->end());
		++collection_size;
	}
	// The following is called L in the pseudocode
	std::map<int, int, bool (*)(int,int)> intersection_sizes_counts(reverse_int_comp);
	// The following is called D_C in the pseudocode
	std::set<std::set<int> > intersections;
	std::string line;
	int size = 0;
	while (std::getline(dataset_s, line)) {
		++size;
		const std::set<int> tau = string2itemset(line);
		std::vector<int> intersection_v(tau.size());
		std::vector<int>::iterator it;
		it = std::set_intersection(
				tau.begin(), tau.end(), items.begin(), items.end(),
				intersection_v.begin());
		if (it != intersection_v.begin() && it - intersection_v.begin() != items.size()) {
			std::set<int> intersection(intersection_v.begin(), it);
			std::pair<std::set<std::set<int> >::iterator, bool> insertion_pair = intersections.insert(intersection);
			if (insertion_pair.second) { // intersection was not already in intersections
				std::map<int, int, bool (*)(int,int)>::iterator intersection_it = intersection_sizes_counts.find(intersection.size());
				if (intersection_it == intersection_sizes_counts.end()) { // we've never seen an intersection of this size
					int prev_value = 0; // We add an element with key equal to the intersection size, and value equal to the value of the element with key immediately larger thn this one, or 0 if there is no such element.
					if (! intersection_sizes_counts.empty()) {
						auto longer_intersection_it = intersection_sizes_counts.lower_bound(intersection.size());
						if (longer_intersection_it != intersection_sizes_counts.begin()) {
							--longer_intersection_it;
							prev_value = longer_intersection_it->second;
						}
					}
					intersection_it = (intersection_sizes_counts.emplace(intersection.size(), prev_value)).first;
				}
				// Exploit the sorted nature (in decreasing order) of the map
				for (; intersection_it != intersection_sizes_counts.end(); ++intersection_it) {
					intersection_sizes_counts[intersection_it->first] += 1;
				}
			}
		}
	}
	dataset_s.close();
	dataset.set_size(size); // Set size in the database object
	// We do not need a counter 'i' like in the pseudocode, we can use an
	// iterator that exploits the sorted nature of the map
	std::map<int, int, bool (*)(int,int)>::iterator it = intersection_sizes_counts.begin();
	IloEnv env;
	IloModel model(env);
	if (get_CPLEX_model(model, env, items, collection, it->first, stats_conf.use_antichain) == -1) {
		std::cerr << "ERROR: something went wrong while building the CPLEX model" << std::endl;
		env.end();
		std::exit(EXIT_FAILURE);
	}
	IloCplex cplex(model);
	// Set parameters, like max runtime and tolerance gaps
	set_CPLEX_params(cplex);
	// Redirect output to null stream
	cplex.setOut(env.getNullStream());
	// Iterate over the possible lengths
	while (true) {
		// The following is q in the pseudocode
		double profit = get_SUKP_profit(cplex);
		if (profit == -1.0) {
			std::cerr << "ERROR: something went wrong while solving the SUKP" << std::endl;
			env.end();
			std::exit(EXIT_FAILURE);
		}
		// This is b in the pseudocode
		int bound =  ((int) floor(log2(profit))) + 1;
		if (bound <= it->second) {
			result.first = bound;
			result.second = -1;
			env.end();
			return 1;
		} else {
			++it;
			if (it != intersection_sizes_counts.end()) {
				if (it->first == 1) {
					result.first = 1;
					result.second = -1;
					env.end();
					return 1;
				}
				set_capacity(model, it->first);
			} else {
				env.end();
				break;
			}
		}
	}
	--it;
	// XXX TODO The following needs to be checked a bit: it may not be the best.
	result.first = (int) floor(fmin(it->second, log2(collection_size)));
	result.second = -1;
	env.end();
	return 1;
}
Esempio n. 18
0
int SolveLpByRuleGeneral(const RULES InputRule,
	const std::vector<REQ> &Request,
	const std::vector<DAY> &Day,
	const std::vector<AIRLINE> &AirLine,
	std::vector<CAPCONSTRAIN> &CapCon,
	std::vector<double> &SolVal)
{
	try{
		ofstream CheckSolStatus;
		CheckSolStatus.open("..//OutPut//CplexSatus.txt", ios::trunc);
		IloBool SolErr= 0;
		double CurrentProportionEps;
		if (isIterativeReduceEps)
		{
			CurrentProportionEps = StartingProptionEps;
		}
		else
		{
			CurrentProportionEps = ProportionFairEps;
		}
		std::vector<int> ReqSecq2Var;//map Request sequence to variable location
		std::vector<int> Var2ReqSecq;// revers map Var to request sequence
		std::vector<int> ReqSecq2ID; // map request sequence to request ID
		std::vector<int> ReqSecq2DumVar;  // map request to dummy variable locations
		std::vector<int> ID2ReqSecq(Request.size(), InvalidInt);// map request ID to reqeuset secquence
		std::vector<int> Rio2AirLine;// 

		int NumActRow = 0;
		int NumVar =
			getNumVar(InputRule, Request, ReqSecq2Var, Var2ReqSecq,
			ReqSecq2ID, ID2ReqSecq, ReqSecq2DumVar);
		int NumAirLineByRule = getAirNumVar(InputRule, AirLine, Rio2AirLine);
		assert(NumVar > 0); assert(NumAirLineByRule > 0);
		int Pos;
		double obj = 0.0;
		IloEnv env;
		/***********create variable***************/
		IloNumVarArray Xmt(env, NumVar, 0, 1, ILOINT);
		//IloNumVar DummyTotalObj(env);

		//IloNumVarArray Xmt(env, NumVar, 0, 1, ILOFLOAT);

		IloModel LpModel(env);
		IloExpr TotalDispExp(env);
		IloExpr WeightedTotalDispExp(env);
		IloExpr FairObjExp(env);
		IloExprArray GainEpr(env, Rio2AirLine.size()), LossEpr(env, Rio2AirLine.size());
		for (int i = 0; i < Rio2AirLine.size(); i++)
		{
			GainEpr[i] = IloExpr(env);
			LossEpr[i] = IloExpr(env);
		}
		/***********Add objective Function***************/
		//setDispObj(InputRule, env, LpModel, DummyDisplaceObj, Xmt, Rio2AirLine, Request, AirLine, ID2ReqSecq, ReqSecq2Var, ReqSecq2DumVar);

		getDispExps(InputRule, env, LpModel, TotalDispExp, WeightedTotalDispExp, Xmt, Rio2AirLine, Request, AirLine, ID2ReqSecq, ReqSecq2Var, ReqSecq2DumVar);
		//LpModel.add(DummyTotalObj >= TotalDispExp);
		IloObjective OBJ = IloMinimize(env);
		//set displacement objective

		if (DispObj == Disp)
		{
			OBJ.setExpr(TotalDispExp);
			//OBJ.setExpr(DummyTotalObj);
		}
		if (DispObj == WeightDisp)
		{
			OBJ.setExpr(WeightedTotalDispExp);
		}
		
		LpModel.add(OBJ);
		/***********Add definational constraints***************/
		setDefCon(InputRule, env, LpModel, Xmt, Request, ReqSecq2Var, ID2ReqSecq, ReqSecq2DumVar);
		/***********Solve the cplex model***************/
		IloCplex cplex(env);
		cplex.setOut(env.getNullStream());
#ifdef DEBUG
		cplex.setOut(CplexLog);
#endif
		cplex.setParam(IloCplex::Param::TimeLimit, CplexMaxCpuTime);
		//cplex.setParam(IloCplex::Param::MIP::Tolerances::MIPGap, CplexRelGap);

		/*if (FairObj!=NoFair)
			cplex.setParam(IloCplex::Param::MIP::Tolerances::MIPGap, CplexRelGap);*/
		cplex.extract(LpModel);
		SolErr = cplex.solve();
		CheckSolStatus << cplex.getCplexStatus() << "\t" << SolErr << "\t" << cplex.getMIPRelativeGap() << "\t" << cplex.getCplexTime() << endl;
		//cout << "obj = "<<cplex.getObjValue() << endl;
		/***********Add violated constraints***************/

		IloExprArray NewCons(env);
		addVioCapConByDay(InputRule, env, LpModel, cplex, NewCons, Xmt, CapCon, Request, Day, ReqSecq2Var, ID2ReqSecq);
		addTurnRoundCon(InputRule, env, LpModel, cplex, NewCons, Xmt, Request, ReqSecq2Var, ID2ReqSecq);

		while (NewCons.getSize() > 0)
		{
			for (int i = 0; i < NewCons.getSize(); i++)
			{
				LpModel.add(NewCons[i]);
			}
			NumActRow += (int)NewCons.getSize();
			cplex.extract(LpModel);
			SolErr = cplex.solve();
			CheckSolStatus << cplex.getCplexStatus() << "\t" << SolErr <<"\t"<<cplex.getMIPRelativeGap()<<"\t"<<cplex.getCplexTime()<<endl;
			//printf("disp = %f \n", cplex.getValue(TotalDispExp));
			//if (FairObj == EnvyFun)
			//{
			//	printf("disp = %f \n", cplex.getValue(DummyDisplaceObj));
			//	printf("envy obj = %f \n", cplex.getValue(FairObjExp));
			//}
			NewCons.clear();
			addVioCapConByDay(InputRule, env, LpModel, cplex, NewCons, Xmt, CapCon, Request, Day, ReqSecq2Var, ID2ReqSecq);
			addTurnRoundCon(InputRule, env, LpModel, cplex, NewCons, Xmt, Request, ReqSecq2Var, ID2ReqSecq);
		}
#ifdef DEBUG
		cout << "Dummy displacment obj ="<<cplex.getValue(TotalDispExp) <<" expre value"<<cplex.getValue(TotalDispExp)<< endl;
#endif
		
		if (FairObj == EnvyFun){
BiObj:
			LpModel.remove(OBJ);
			GetEnvyLossAndGainExp(InputRule, env, LpModel, GainEpr, LossEpr, Xmt, Rio2AirLine, Request, AirLine, ID2ReqSecq, ReqSecq2Var, ReqSecq2DumVar);
			FairObjExp.clear();
			for (int i = 0; i < Rio2AirLine.size(); i++)
			{
				FairObjExp += EnvyGainWeight*GainEpr[i] + EnvyLossWeight*LossEpr[i];
			}
			OBJ.setExpr(EnvyFairWeight*FairObjExp + TotalDispExp);
			LpModel.add(OBJ);
			cplex.extract(LpModel);
			SolErr = cplex.solve();
			//CheckSolStatus << cplex.getCplexStatus() << "\t" << SolErr << endl;
			//printf("disp = %f \n", cplex.getValue(TotalDispExp));
			//printf("envy obj = %f \n", cplex.getValue(FairObjExp));
			//GetEnvyLossAndGainValue(InputRule, env, LpModel, cplex, Xmt, Rio2AirLine, Request, AirLine, ID2ReqSecq, ReqSecq2Var, ReqSecq2DumVar);
			//for (int i = 0; i < Rio2AirLine.size(); i++)
			//{
			//	//LogMsg("gain = %f, loss = %f \n", cplex.getValue(Gain[i]), cplex.getValue(Loss[i]));
			//	LogMsg("gain = %f, loss = %f \n", cplex.getValue(GainEpr[i]), cplex.getValue(LossEpr[i]));
			//}
			NewCons.clear();
			addVioCapConByDay(InputRule, env, LpModel, cplex, NewCons, Xmt, CapCon, Request, Day, ReqSecq2Var, ID2ReqSecq);
			addTurnRoundCon(InputRule, env, LpModel, cplex, NewCons, Xmt, Request, ReqSecq2Var, ID2ReqSecq);
		
			while (NewCons.getSize() > 0)
			{
				for (int i = 0; i < NewCons.getSize(); i++)
				{
					LpModel.add(NewCons[i]);
				}
				NumActRow += (int)NewCons.getSize();
				cplex.extract(LpModel);
				SolErr = cplex.solve();
			
				CheckSolStatus << cplex.getCplexStatus() << "\t" << SolErr << "\t" << cplex.getMIPRelativeGap() << "\t" << cplex.getCplexTime() << endl;
				
				printf("disp = %f \n", cplex.getValue(TotalDispExp));
				printf("envy obj = %f \n", cplex.getValue(FairObjExp));
				NewCons.clear();
				addVioCapConByDay(InputRule, env, LpModel, cplex, NewCons, Xmt, CapCon, Request, Day, ReqSecq2Var, ID2ReqSecq);
				addTurnRoundCon(InputRule, env, LpModel, cplex, NewCons, Xmt, Request, ReqSecq2Var, ID2ReqSecq);
			}
			if (SolErr == 0)
			{// resolve displcement first
				LpModel.remove(OBJ);
				OBJ.setExpr(TotalDispExp);
				LpModel.add(OBJ);
				cplex.extract(LpModel);
				SolErr = cplex.solve();
				CheckSolStatus << cplex.getCplexStatus() << "\t" << SolErr << "\t" << cplex.getMIPRelativeGap() << "\t" << cplex.getCplexTime() << endl;
				cout << "reinitialize is called" << endl;

				if (SolErr == 0)
				{
					cout << "Resolve falils" << endl;
					system("Pause");
				}
				else
				{
					goto BiObj;
				}
			}
		}


	AddFairEpsConstraint:
		int totalFairConstraint = 0;
		if (ProportionFairEps>MyZero&&EpsCon != NoEps)
		{
			NewCons.clear();
			addEpsConstraint(InputRule, env, LpModel,  Xmt, cplex, NewCons, Rio2AirLine, Request, AirLine, ID2ReqSecq, ReqSecq2Var, ReqSecq2DumVar, CurrentProportionEps);
			totalFairConstraint += (int)NewCons.getSize();
			while (NewCons.getSize() > 0)
			{
				for (int i = 0; i < NewCons.getSize(); i++)
				{
					LpModel.add(NewCons[i]);
				}
				NumActRow += (int)NewCons.getSize();
				cplex.extract(LpModel);
				SolErr = cplex.solve();
				CheckSolStatus << cplex.getCplexStatus() << "\t" << SolErr << "\t" << cplex.getMIPRelativeGap() << "\t" << cplex.getCplexTime() << endl;
//#ifdef DEBUG
				//cout << "Dummy displacment obj ="<<cplex.getValue(DummyDisplaceObj) <<" expre value"<<cplex.getValue(TotalDispExp)<< endl;
				//cout << "Total fair constraint added is " << totalFairConstraint << "; Obj = " <<cplex.getObjValue() << endl;
//#endif // DEBUG
				NewCons.clear();
				//addFairConstraints(InputRule, env, LpModel, DummyDisplaceObj, Xmt, cplex, NewCons, Rio2AirLine, Request, AirLine, ID2ReqSecq, ReqSecq2Var, ReqSecq2DumVar);
				addEpsConstraint(InputRule, env, LpModel,  Xmt, cplex, NewCons, Rio2AirLine, Request, AirLine, ID2ReqSecq, ReqSecq2Var, ReqSecq2DumVar, CurrentProportionEps);
				totalFairConstraint += (int)NewCons.getSize();
				//addAbsFairnessConstraint(InputRule, env, LpModel, DummyDisplaceObj, Xmt, cplex, NewCons, Rio2AirLine, Request, AirLine, ID2ReqSecq, ReqSecq2Var, ReqSecq2DumVar);
				addVioCapConByDay(InputRule, env, LpModel, cplex, NewCons, Xmt, CapCon, Request, Day, ReqSecq2Var, ID2ReqSecq);
				addTurnRoundCon(InputRule, env, LpModel, cplex, NewCons, Xmt, Request, ReqSecq2Var, ID2ReqSecq);
			}
		}
		// iterative add eps constraints
		if (CurrentProportionEps > ProportionFairEps && (ProportionFairEps > MyZero) && EpsCon != NoEps)
		{
			if (isIterativeReduceEps)
			{
				CurrentProportionEps = std::max(CurrentProportionEps - 0.1, ProportionFairEps);
				goto AddFairEpsConstraint;
			}

		}

		if (isSolveByRule) UpdateCapConByDay(InputRule, cplex, Xmt, CapCon, Request, Day, ReqSecq2Var, ID2ReqSecq);
		//compute for the weighted
		//set SolValue
		for (auto r = Request.begin(); r != Request.end(); r++)
		{
			if (isSolveByRule)
			{
				if (r->Rule != InputRule) continue;
			}
			for (int t = 0; t < NT; t++)
			{
				Pos = ReqSecq2Var[ID2ReqSecq[r->ID]] + t;
				SolVal[r->ID*NT + t] = cplex.getValue(Xmt[Pos]);
			}
			if (isIngoreDummy) continue;
			SolVal[Request.size()*NT + r->ID] = cplex.getValue(Xmt[ReqSecq2DumVar[ID2ReqSecq[r->ID]]]);
		}

		TestCaseSum.back().NumRowGenByRule[InputRule] = NumActRow;
		CheckSolStatus.close();

		TestCaseSum.back().CplexRelativeGapByRule[InputRule] = cplex.getMIPRelativeGap();



		env.end();
		return 0;
	}
	catch (IloException& e) {
		ofstream FinalOut;
		if (isDefaultFolder) FinalOut.open("..//OutPut//Summary.txt", ios::app);
		else FinalOut.open((OutPutFolder + "Summary.txt").c_str(), ios::app);

		FinalOut << "************Warning on cplex****************" << endl;
		cerr << " ERROR: " << e << endl;
		FinalOut << " ERROR: " << e << endl;
		FinalOut.close();
		return 1;
	}
	catch (...) {
		cerr << " ERROR" << endl;
		return 1;
	}
}