void CPLEX_LP_IMSTSolver_v2::generateFlowVariables() {
	EdgeIdx edgeIdCount { };
	VertexIdx sourceVertexIdx { };
	VertexIdx targetVertexIdx { };
	EdgeIF* edge { };
	VertexIF* vertex { };

	flowVariables = IloNumVarArray(env, 2 * numberOfEdges, 0, IloInfinity);

	INFO_NOARG(logger, LogBundleKey::CPLPIMST2_FLOW_GEN);

	if (graph->hasAnyVertex(Visibility::VISIBLE)) {
		initialVertexIdx = graph->nextVertex()->getVertexIdx();

		INFO(logger, LogBundleKey::CPLPIMST2_FLOW_GEN_INIT_NODE,
				initialVertexIdx);

		flowVariablesMap.insert(
				std::make_pair(initialVertexIdx,
						IloTargetVertexFlowVarMap { }));

		while (graph->hasNextVertex(Visibility::VISIBLE)) {
			flowVariablesMap.insert(
					std::make_pair(graph->nextVertex()->getVertexIdx(),
							IloTargetVertexFlowVarMap { }));
		}

		edgeIdCount = 0;

		graph->beginEdge();
		while (graph->hasNextEdge(Connectivity::CONNECTED, Visibility::VISIBLE)) {
			edge = graph->nextEdge();
			sourceVertexIdx = edge->getSourceVertex()->getVertexIdx();
			targetVertexIdx = edge->getTargetVertex()->getVertexIdx();

			INFO(logger, LogBundleKey::CPLPIMST2_FLOW_GEN_VAR, sourceVertexIdx,
					targetVertexIdx,
					getVariableName(flowVariables[edgeIdCount]).c_str());

			flowVariablesMap.at(sourceVertexIdx).insert(
					std::make_pair(targetVertexIdx,
							flowVariables[edgeIdCount]));

			edgeIdCount += 1;

			INFO(logger, LogBundleKey::CPLPIMST2_FLOW_GEN_VAR, sourceVertexIdx,
					targetVertexIdx,
					getVariableName(flowVariables[edgeIdCount]).c_str());

			flowVariablesMap.at(targetVertexIdx).insert(
					std::make_pair(sourceVertexIdx,
							flowVariables[edgeIdCount]));

			edgeIdCount += 1;
		}
	}
}
Beispiel #2
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();    
 }
Beispiel #3
0
int createVars(const Problem<double>& P, IloEnv& env, IloNumVarMatrix& x, IloNumVarMatrix& y, IloNumVarMatrix& b, IloNumVarMatrix& w){
  try{
    int i;
    const int nbTask=P.nbTask;
    const int E= 2*nbTask;
    
    for (i=0;i<nbTask;i++){
      x[i]=IloNumVarArray(env, E, 0, 1, ILOINT);
      y[i]=IloNumVarArray(env, E, 0, 1, ILOINT);
      b[i]=IloNumVarArray(env, E-1, 0, ((P.d(i)-P.r(i))*P.bmax(i)), ILOFLOAT);
      w[i]=IloNumVarArray(env, E-1, 0, (P.d(i)-P.r(i))*P.A[i].Fi(P.bmax(i)), ILOFLOAT);
  }  
  return 0;
}
catch (IloException &e){
  std::cout << "iloexception in create vars" <<e <<std::endl;
  e.end();
  return  1;
 }
}
void CPLEX_LP_IMSTSolver_v2::createEdgeVariables(GraphIF * const graph,
		IloNumVar::Type edgeVariablesType) {
	EdgeIdx edgeId { };
	VertexIdx sourceVertexIdx { };
	VertexIdx targetVertexIdx { };
	EdgeIF* edge { };
	IteratorId edgeIterator = graph->getEdgeIteratorId();

	INFO(logger, LogBundleKey::CPLPIMST2_EDGE_VAR_GEN,
			graph->getNumberOfEdges(Visibility::VISIBLE),
			EnumUtils::getLPVariableTypeString(
					static_cast<unsigned int>(edgeVariablesType)));
	edgeVariableArray = IloNumVarArray(env,
			graph->getNumberOfEdges(Visibility::VISIBLE), 0, 1,
			edgeVariablesType);
	model.add(edgeVariableArray);

	graph->beginEdge(edgeIterator);

	while (graph->hasNextEdge(edgeIterator, Connectivity::CONNECTED,
			Visibility::VISIBLE)) {
		edge = graph->nextEdge(edgeIterator);
		sourceVertexIdx = edge->getSourceVertex()->getVertexIdx();
		targetVertexIdx = edge->getTargetVertex()->getVertexIdx();

		if (edgeVariableMap.count(sourceVertexIdx) == 0) {
			edgeVariableMap.insert(
					std::make_pair(sourceVertexIdx,
							IloTargetVertexEdgeVarMap()));
		}

		edgeVariableMap.at(sourceVertexIdx).insert(
				std::make_pair(targetVertexIdx,
						std::make_pair(edgeVariableArray[edgeId], edge)));

		INFO(logger, LogBundleKey::CPLPIMST2_EDGE_VAR_ADD,
				LogStringUtils::edgeVisualization(
						edgeVariableMap.at(sourceVertexIdx).at(targetVertexIdx).second,
						"\t").c_str(), sourceVertexIdx, targetVertexIdx,
				getVariableName(
						edgeVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first).c_str());

		edgeId += 1;
	}

	graph->removeEdgeIterator(edgeIterator);
}
Beispiel #5
0
DataVarNumMatrix::DataVarNumMatrix(string name, double borne, IloEnv env,int n, int m){
	this->Matrix = IloArray<IloNumVarArray> (env,n);
	for(int i = 0; i < n; i++){
		this->Matrix[i] = IloNumVarArray(env,m,0,borne);
		for(int j = 0; j < m; j++){
			string var_name = name;//attribut à nom de la forme x(i,j) à la variable
			var_name += "(";
			var_name += U::to_s(i+1);
			var_name += ",";
			var_name += U::to_s(j+1);
			var_name += ")";


			this->Matrix[i][j] = IloNumVar(env,0,borne,var_name.c_str());

		}
	}

	this->n = n;
	this->m = m;
}
Beispiel #6
0
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;
}
Beispiel #7
0
int
main(int argc)
{


	IloEnv   env;
	try {
		IloModel model(env);

		NumVarMatrix varOutput(env, J + current);
		NumVar3Matrix varHelp(env, J + current);
		Range3Matrix cons(env, J + current);
		for (int j = 0; j <J + current; j++){
			varOutput[j] = IloNumVarArray(env, K);
			varHelp[j] = NumVarMatrix(env, K);
			cons[j] = RangeMatrix(env, K);
			for (int k = 0; k < K; k++){
				varOutput[j][k] = IloNumVar(env, 0.0, IloInfinity);
				varHelp[j][k] = IloNumVarArray(env, L);
				cons[j][k] = IloRangeArray(env, C);
				for (int l = 0; l < L; l++){
					varHelp[j][k][l] = IloNumVar(env, 0.0, IloInfinity);
				}
				if (j > current){
					cons[j][k][0] = IloRange(env, 0.0, 0.0);//will be used to express equality of varOutput, constraint (0)
					cons[j][k][1] = IloRange(env, 0.0, IloInfinity);// constraint (1)
					cons[j][k][2] = IloRange(env, -IloInfinity, T[j] - Tdc - Tblow[j] - Tslack);// constraint (2)
					cons[j][k][3] = IloRange(env, Tfd[k], Tfd[k]);// constraint (3)
					cons[j][k][4] = IloRange(env, 0.0, IloInfinity);// constraint (4)
					cons[j][k][5] = IloRange(env, Tdf[k], IloInfinity);// constraint (5)
					cons[j][k][6] = IloRange(env, T[j - a[k]] + Tcd, T[j - a[k]] + Tcd);// constraint (6)
					cons[j][k][7] = IloRange(env, TlossD[k], IloInfinity);// constraint (7)
					cons[j][k][8] = IloRange(env, TlossF[k], IloInfinity);// constraint (8)
				}
			}
		}

		populatebynonzero(model, varOutput, varHelp, cons);

		IloCplex cplex(model);

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

		IloNumArray vals(env);
		IloNumVar val(env);

		//vars to save output
		double TimeAvailable[J][K];
		double TimeInstances[J][K][L];
		double LK103[J][2];


		env.out() << "Solution status = " << cplex.getStatus() << endl;
		env.out() << "Solution value  = " << cplex.getObjValue() << endl;
		for (int j = current; j < current + J; ++j)
		{
			cplex.getValues(vals, varOutput[j]);
			env.out() << "Seconds for load "<<j<<"       = " << vals << endl;
			/*for (int k = 0; k < K; k++){
				TimeAvailable[j][k] = cplex.getValue(varOutput[j][k]);
			}*/
		}
		for (int j = current; j < current + J; j++){
			for (int k = 0; k < K; k++){
				cplex.getValues(vals, varHelp[j][k]);
				env.out() << "Time instances for spoon "<<k<<" in load "<<j<<" = " << vals << endl;
				/*for (int l = 0; l < L; l++){
					TimeInstances[j][k][l] = cplex.getValue(varHelp[j][k][l]);
				}*/
			}
		}

		for (int j = current + 2; j < J + current; j++){
			LK103[j][0] = TimeInstances[j - 2][0][0];
			LK103[j][1] = TimeInstances[j][0][5];
			env.out() << "LK103, load " << j << " : " << LK103[j][1]-LK103[j][0] << endl;
		}
		/*cplex.getSlacks(vals, cons);
		env.out() << "Slacks        = " << vals << endl;
		cplex.getDuals(vals, cons);
		env.out() << "Duals         = " << vals << endl;
		cplex.getReducedCosts(vals, varOutput);
		env.out() << "Reduced Costs = " << vals << endl;*/

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

	env.end();
	cin.get();
	return 0;
}  // END main
void kMST_ILP::modelSCF()
{
	// single commodity flow model

	// flow for each edge
	flow_scf = IloNumVarArray(env, edges.getSize());

	for (unsigned int i=0; i<flow_scf.getSize(); i++) {
		flow_scf[i] = IloNumVar(env, Tools::indicesToString("flow", i).c_str());

		// non-zero
		model.add(0 <= flow_scf[i]);
		// at most k, also ensures that edge is taken if flow is non-zero
		model.add(flow_scf[i] <= k*edges[i]);
	}

	// 0 emits k+1 tokens
	{
		vector<u_int> outgoingEdgeIds;
		getOutgoingEdgeIds(outgoingEdgeIds, 0);

		IloExpr outgoingFlowSum(env);
		for (unsigned int i=0; i<outgoingEdgeIds.size(); i++) {
			outgoingFlowSum += flow_scf[ outgoingEdgeIds[i] ];
		}

		model.add(outgoingFlowSum == k);
	}

	// flow conservation, each node, which is taken, eats one (except first)
	{
		vector<u_int> outgoingEdgeIds;
		getOutgoingEdgeIds(outgoingEdgeIds, 0);

		for (unsigned int vertex=1; vertex<instance.n_nodes; vertex++) {
			vector<u_int> outgoingEdgeIds, incomingEdgeIds;

			getIncomingEdgeIds(incomingEdgeIds, vertex);

			IloExpr incomingFlowSum(env);
			IloExpr incomingEdgesSum(env);
			for (unsigned int i=0; i<incomingEdgeIds.size(); i++) {
				incomingFlowSum += flow_scf[ incomingEdgeIds[i] ];
				incomingEdgesSum += edges[ incomingEdgeIds[i] ];
			}

			getOutgoingEdgeIds(outgoingEdgeIds, vertex);
			IloExpr outgoingFlowSum(env);
			for (unsigned int i=0; i<outgoingEdgeIds.size(); i++) {
				outgoingFlowSum += flow_scf[ outgoingEdgeIds[i] ];
			}

			// vertex is part solution if one incoming vertex is used

			model.add(incomingFlowSum - outgoingFlowSum == incomingEdgesSum);

			incomingFlowSum.end();
			incomingEdgesSum.end();
			outgoingFlowSum.end();
		}
	}
}
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;
}
Beispiel #10
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();
 }
Beispiel #11
0
int
main()
{
    IloEnv env;
    try {
        NumMatrix cost(env, nbMonths);
        cost[0]=IloNumArray(env, nbProducts, 110.0, 120.0, 130.0, 110.0, 115.0);
        cost[1]=IloNumArray(env, nbProducts, 130.0, 130.0, 110.0,  90.0, 115.0);
        cost[2]=IloNumArray(env, nbProducts, 110.0, 140.0, 130.0, 100.0,  95.0);
        cost[3]=IloNumArray(env, nbProducts, 120.0, 110.0, 120.0, 120.0, 125.0);
        cost[4]=IloNumArray(env, nbProducts, 100.0, 120.0, 150.0, 110.0, 105.0);
        cost[5]=IloNumArray(env, nbProducts,  90.0, 100.0, 140.0,  80.0, 135.0);

        // Variable definitions
        IloNumVarArray produce(env, nbMonths, 0, IloInfinity);
        NumVarMatrix   use(env, nbMonths);
        NumVarMatrix   buy(env, nbMonths);
        NumVarMatrix   store(env, nbMonths);
        IloInt i, p;
        for (i = 0; i < nbMonths; i++) {
            use[i]   = IloNumVarArray(env, nbProducts, 0, IloInfinity);
            buy[i]   = IloNumVarArray(env, nbProducts, 0, IloInfinity);
            store[i] = IloNumVarArray(env, nbProducts, 0, 1000);
        }
        IloExpr profit(env);

        IloModel model(env);

        // For each type of raw oil we must have 500 tons at the end
        for (p = 0; p < nbProducts; p++) {
            store[nbMonths-1][p].setBounds(500, 500);
        }

        // Constraints on each month
        for (i = 0; i < nbMonths; i++) {
            // Not more than 200 tons of vegetable oil can be refined
            model.add(use[i][v1] + use[i][v2] <= 200);

            // Not more than 250 tons of non-vegetable oil can be refined
            model.add(use[i][o1] + use[i][o2] + use[i][o3] <= 250);

            // Constraints on food composition
            model.add(3 * produce[i] <=
                      8.8 * use[i][v1] + 6.1 * use[i][v2] +
                      2   * use[i][o1] + 4.2 * use[i][o2] + 5 * use[i][o3]);
            model.add(8.8 * use[i][v1] + 6.1 * use[i][v2] +
                      2   * use[i][o1] + 4.2 * use[i][o2] + 5 * use[i][o3]
                      <= 6 * produce[i]);
            model.add(produce[i] == IloSum(use[i]));

            // Raw oil can be stored for later use
            if (i == 0) {
                for (IloInt p = 0; p < nbProducts; p++)
                    model.add(500 + buy[i][p] == use[i][p] + store[i][p]);
            }
            else {
                for (IloInt p = 0; p < nbProducts; p++)
                    model.add(store[i-1][p] + buy[i][p] == use[i][p] + store[i][p]);
            }

            // Logical constraints
            // The food cannot use more than 3 oils
            // (or at least two oils must not be used)
            model.add((use[i][v1] == 0) + (use[i][v2] == 0) + (use[i][o1] == 0) +
                      (use[i][o2] == 0) + (use[i][o3] == 0) >= 2);

            // When an oil is used, the quantity must be at least 20 tons
            for (p = 0; p < nbProducts; p++)
                model.add((use[i][p] == 0) || (use[i][p] >= 20));

            // If products v1 or v2 are used, then product o3 is also used
            model.add(IloIfThen(env, (use[i][v1] >= 20) || (use[i][v2] >= 20),
                                use[i][o3] >= 20));

            // Objective function
            profit += 150 * produce[i] - IloScalProd(cost[i], buy[i]) -
                      5 * IloSum(store[i]);
        }

        // Objective function
        model.add(IloMaximize(env, profit));

        IloCplex cplex(model);

        if (cplex.solve()) {
            cout << "Solution status: " << cplex.getStatus() << endl;
            cout << " Maximum profit = " << cplex.getObjValue() << endl;
            for (IloInt i = 0; i < nbMonths; i++) {
                IloInt p;
                cout << " Month " << i << " " << endl;
                cout << "  . buy   ";
                for (p = 0; p < nbProducts; p++) {
                    cout << cplex.getValue(buy[i][p]) << "\t ";
                }
                cout << endl;
                cout << "  . use   ";
                for (p = 0; p < nbProducts; p++) {
                    cout << cplex.getValue(use[i][p]) << "\t ";
                }
                cout << endl;
                cout << "  . store ";
                for (p = 0; p < nbProducts; p++) {
                    cout << cplex.getValue(store[i][p]) << "\t ";
                }
                cout << endl;
            }
        }
        else {
            cout << " No solution found" << endl;
        }
    }
    catch (IloException& ex) {
        cerr << "Error: " << ex << endl;
    }
    catch (...) {
        cerr << "Error" << endl;
    }
    env.end();
    return 0;
}
Beispiel #12
0
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);
      }
Beispiel #13
0
int
main(int argc, char **argv)
{
   IloEnv env;
   try {
      IloInt i, j;

      IloNumArray capacity(env), fixedCost(env);
      FloatMatrix cost(env);
      IloInt      nbLocations;
      IloInt      nbClients;

      const char* filename  = "../../../examples/data/facility.dat";
      if (argc > 1) 
         filename = argv[1];
      ifstream file(filename);
      if (!file) {
         cerr << "ERROR: could not open file '" << filename
              << "' for reading" << endl;
         cerr << "usage:   " << argv[0] << " <file>" << endl;
         throw(-1);
      }

      file >> capacity >> fixedCost >> cost;
      nbLocations = capacity.getSize();
      nbClients   = cost.getSize(); 

      IloBool consistentData = (fixedCost.getSize() == nbLocations);
      for(i = 0; consistentData && (i < nbClients); i++)
         consistentData = (cost[i].getSize() == nbLocations);
      if (!consistentData) {
         cerr << "ERROR: data file '" 
              << filename << "' contains inconsistent data" << endl;
         throw(-1);
      }

      IloNumVarArray open(env, nbLocations, 0, 1, ILOINT);
      NumVarMatrix supply(env, nbClients);
      for(i = 0; i < nbClients; i++)
         supply[i] = IloNumVarArray(env, nbLocations, 0, 1, ILOINT);

      IloModel model(env);
      for(i = 0; i < nbClients; i++)
         model.add(IloSum(supply[i]) == 1);
      for(j = 0; j < nbLocations; j++) {
         IloExpr v(env);
         for(i = 0; i < nbClients; i++)
            v += supply[i][j];
         model.add(v <= capacity[j] * open[j]);
         v.end();
      }

      IloExpr obj = IloScalProd(fixedCost, open);
      for(i = 0; i < nbClients; i++) {
         obj += IloScalProd(cost[i], supply[i]);
      }
      model.add(IloMinimize(env, obj));
      obj.end();

      IloCplex cplex(env);
      cplex.extract(model);
      cplex.solve();
	
      cplex.out() << "Solution status: " << cplex.getStatus() << endl;

      IloNum tolerance = cplex.getParam(
         IloCplex::Param::MIP::Tolerances::Integrality);
      cplex.out() << "Optimal value: " << cplex.getObjValue() << endl;
      for(j = 0; j < nbLocations; j++) {
         if (cplex.getValue(open[j]) >= 1 - tolerance) {
            cplex.out() << "Facility " << j << " is open, it serves clients ";
            for(i = 0; i < nbClients; i++) {
               if (cplex.getValue(supply[i][j]) >= 1 - tolerance)
                  cplex.out() << i << " ";
            }
            cplex.out() << endl; 
         }
      }
   }
   catch(IloException& e) {
      cerr  << " ERROR: " << e << endl;   
   }
   catch(...) {
      cerr  << " ERROR" << endl;   
   }
   env.end();
   return 0;
}
Beispiel #14
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();
}
Beispiel #15
0
int
main (void)
{
   IloEnv   env;
   try {
      IloModel model(env);
      IloCplex cplex(env);

      IloInt nbWhouses = 4;
      IloInt nbLoads = 31;
      IloInt w, l;

      IloNumVarArray capVars(env, nbWhouses, 0, 10, ILOINT); // Used capacities
      IloNumArray    capLbs (env, nbWhouses, 2, 3, 5, 7); // Minimum usage level
      IloNumArray    costs  (env, nbWhouses, 1, 2, 4, 6); // Cost per warehouse

      // These variables represent the assigninment of a
      // load to a warehouse.
      IloNumVarArrayArray assignVars(env, nbWhouses); 
      for (w = 0; w < nbWhouses; w++) {
         assignVars[w] = IloNumVarArray(env, nbLoads, 0, 1, ILOINT);

         // Links the number of loads assigned to a warehouse with 
         // the capacity variable of the warehouse.
         model.add(IloSum(assignVars[w]) == capVars[w]);
      }

      // Each load must be assigned to just one warehouse.
      for (l = 0; l < nbLoads; l++) {
         IloNumVarArray aux(env);
         for (w = 0; w < nbWhouses; w++)
            aux.add(assignVars[w][l]);
         model.add(IloSum(aux) == 1);
         aux.end();
      }

      model.add (IloMinimize(env, IloScalProd(costs, capVars)));

      cplex.extract(model);
      cplex.setParam(IloCplex::Param::MIP::Strategy::Search, IloCplex::Traditional);
      if ( cplex.solve(SemiContGoal(env, capVars, capLbs)) ) {
         cout << " --------------------------------------------------" << endl;
         cout << "Solution status: " << cplex.getStatus() << endl;
         cout << endl << "Solution found:" << endl;
         cout << " Objective value = " 
              << cplex.getObjValue() << endl << endl;
         for (w = 0; w < nbWhouses; w++) {
            cout << "Warehouse " << w << ": stored " 
                 << cplex.getValue(capVars[w]) << " loads" << endl;
            for (l = 0; l < nbLoads; l++) {
               if ( cplex.getValue(assignVars[w][l]) > 1e-5 )
                  cout << "Load " << l << " | ";
            }
            cout << endl << endl;
         }
         cout << " --------------------------------------------------" << endl;
      } 
      else {
         cout << " No solution found " << endl;
      }

   }
   catch (IloException& e) {
      cerr << "Concert exception caught: " << e << endl;
   }

   env.end();

   return 0;
}  // END main
Beispiel #16
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