void CPLEX_LP_IMSTSolver_v2::generateMSTConstraint() {
	INFO(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_IMST_CONSTRAINT,
			graph->getNumberOfVertices(Visibility::VISIBLE) - 1);
	model.add(
			IloSum(edgeVariableArray)
					== graph->getNumberOfVertices(Visibility::VISIBLE) - 1);
}
示例#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();    
 }
示例#3
0
void ScenarioProblem::generateProblem(){

	for(int i=0;i<_sp.getSize();i++){
		if(i>0){
			_sp[i]->generateSubProblem(i,_pd,_scenario,_sp[_sp.getParent(i)]);
		}
		else{
			_sp[i]->generateSubProblem(i,_pd, _scenario);
			
			for(int j=0; j<_pd->getNumberOutages(_scenario) ; j++){
			    _sp[i]->setOutage(_pd->getOutages(_scenario,j), true);
			}
		}

		try{  
  			addSubProblem(i);
		}
		catch (IloEmptyHandleException e)
		{
			cout << "An exception occurred. Exception " << e << endl;
		}

	}


	int stage;
	_sumWeightedDemand=IloExpr(_pd->getEnv());	
	for(int i=0;i<_sp.getSize();i++){
		stage=_sp[i]->getStage();
		_sumWeightedDemand += _pd->getObjWeights(stage)*_sp[i]->getSumD();

		if(i!=0 && _pd->getReDispatch() && _pd->getPenaltyDispatch() ){
			_sumWeightedDemand -= _pd->getPenaltyWeight()*IloSum( _sp[i]->getPDeltaPlus() );


		}
		
	}	
	


}
示例#4
0
void kMST_ILP::addTreeConstraints()
{
	edges = IloBoolVarArray(env, instance.n_edges * 2); // edges in one direction and in other

	// "to"-edges on lower indices
	for (unsigned int i=0; i<instance.n_edges; i++) {
		edges[i] = IloBoolVar(env, Tools::indicesToString("edge " , instance.edges[i].v1, instance.edges[i].v2, instance.edges[i].weight).c_str() );
		//cerr << "init: edge " << i << " from " << instance.edges[i].v1 << " to " << instance.edges[i].v2 << endl;
	}

	// edges in other direction
	for (unsigned int i=instance.n_edges; i<instance.n_edges*2; i++) {
		Instance::Edge edgeInst = instance.edges[ i % instance.n_edges ];
		edges[i] = IloBoolVar(env, Tools::indicesToString("edge " , edgeInst.v2, edgeInst.v1, edgeInst.weight).c_str() );
		//cerr << "init: edge " << i << " from " << instance.edges[i%instance.n_edges].v2 << " to " << instance.edges[i%instance.n_edges].v1 << endl;
	}

	// edges in one direction forbid edges in other direction
	for (unsigned int i=0; i<instance.n_edges; i++) {
		model.add( edges[i] + edges[i + instance.n_edges] <= 1 );
	}

	// exactly k nodes, so k-1 actual edges plus one to the pseudo node 0
	model.add(IloSum(edges) == k);

	// no 2 incoming edges per vertex
	for (unsigned int i=0; i < instance.n_nodes; i++ ){

		IloExpr incomingSum(env);

		{
			vector<u_int> incomingEdgeIds;
			getIncomingEdgeIds(incomingEdgeIds, i);


			for (unsigned int i=0; i < incomingEdgeIds.size(); i++ ){
				incomingSum += edges[incomingEdgeIds[i]];
			}
		}

		model.add(incomingSum <= 1);
		incomingSum.end();
	}

	// only 1 outgoing node from 0
	{
		IloExpr outgoingSum(env);

		bool hasOutgoing = false;
		{
			vector<u_int> outgoingEdges;
			getOutgoingEdgeIds(outgoingEdges, 0);

			for (unsigned int i=0; i<outgoingEdges.size(); i++) {
				hasOutgoing = true;
				outgoingSum += edges[outgoingEdges[i]];
			}
		}

		if (hasOutgoing) { // only true for special input files
			model.add(outgoingSum == 1);
		}
		outgoingSum.end();
	}


	// no incoming to 0
	{
		vector<u_int> incomingEdges;
		getIncomingEdgeIds(incomingEdges, 0);

		for (unsigned int i=0; i<incomingEdges.size(); i++) {
			model.add( edges[incomingEdges[i]] == 0) ;
		}

	}
}
示例#5
0
文件: mixblend.cpp 项目: renvieir/ioc
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;
}
示例#6
0
void ScenarioProblem::addSimProblem(IloModel mod){

	mod.add(_simSP.getP());
	mod.add(_simSP.getD());
	mod.add(_simSP.getTheta());
	
	if(_pd->getGeneratorSwitch()){
		mod.add(_simSP.getY());
	}
	
	if(_pd->getEnergyStorage()){
		mod.add(_simSP.getE());
		mod.add(_simSP.getEDeltaPlus());
		mod.add(_simSP.getEDeltaMinus());
		mod.add(_simSP.getEnergyStorage());
	}

//	if(_pd->getReDispatch()&&index>0){
//		mod.add(_simSP.getPDelta());
//		mod.add(_simSP.getGenReDispatch());
//	}
	if(_pd->getReserve()){
		mod.add(_simSP.getR());
		mod.add(_simSP.getReserveMargin());
	//	if(index>0)	mod.add(_simSP.getRampingCapacity());
	}
	
	mod.add(_simSP.getF());
	mod.add(_simSP.getX());

	if(_pd->getLineSwitch()){
		mod.add(_simSP.getZ());
		mod.add(_simSP.getW());
	}
	
	mod.add(_simSP.getEnergyConservation());
	mod.add(_simSP.getPhaseAngleUp());
	mod.add(_simSP.getPhaseAngleDown());
	mod.add(_simSP.getLineLimitsUp());
	mod.add(_simSP.getLineLimitsDown());

	if(_pd->getCapacity()){
		mod.add(_simSP.getLineLimitsUpM());
		mod.add(_simSP.getLineLimitsDownM());
	}

	if(_pd->getLineSwitch()){
		mod.add(_simSP.getLineSwitch());
		mod.add(_simSP.getLineBurnt());
	}
	mod.add(_simSP.getGenLimitsUp());
	mod.add(_simSP.getGenLimitsDown());

	if(_pd->getEnergyStorage()){
		mod.add(	IloMaximize(	_pd->getEnv(),	_simSP.getSumD()	
					-.1*(  IloSum(_simSP.getEDeltaPlus()) + IloSum(_simSP.getEDeltaMinus())	)	
					));
	}
	else{
		mod.add(	IloMaximize(	_pd->getEnv(),	_simSP.getSumD() ));	
	}


}
示例#7
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;
}
示例#8
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();
 }
示例#9
0
ILOSTLBEGIN


int
main(int, char**)
{
   IloEnv env;
   try {
      IloInt nbMachines = 6;
      IloNumArray cost     (env, nbMachines,
                            15.0, 20.0, 45.0, 64.0, 12.0, 56.0);
      IloNumArray capacity (env, nbMachines,
                            100.0, 20.0, 405.0, 264.0, 12.0, 256.0);
      IloNumArray fixedCost(env, nbMachines,
                            1900.0, 820.0, 805.0, 464.0, 3912.00, 556.0);
      IloNum demand = 22.0;

      IloModel model(env);
      IloNumVarArray x(env, nbMachines, 0, IloInfinity);
      IloNumVarArray fused(env, nbMachines, 0, 1, ILOINT);


      // Objective: minimize the sum of fixed and variable costs
      model.add(IloMinimize(env, IloScalProd(cost, x)
                               + IloScalProd(fused, fixedCost)));

      IloInt i;
      for(i =  0; i < nbMachines; i++) {
        // Constraint: respect capacity constraint on machine 'i'
        model.add(x[i] <= capacity[i]);

        // Constraint: only produce product on machine 'i' if it is 'used'
        //             (to capture fixed cost of using machine 'i')
        model.add(x[i] <= capacity[i]*fused[i]);
      }

      // Constraint: meet demand
      model.add(IloSum(x) == demand);

      IloCplex cplex(env);
      cplex.extract(model);
      cplex.solve();

      cout << "Solution status: " << cplex.getStatus() << endl;

      cout << "Obj " << cplex.getObjValue() << endl;
      IloNum eps = cplex.getParam(
         IloCplex::Param::MIP::Tolerances::Integrality);
      for(i = 0; i < nbMachines; i++) {
         if (cplex.getValue(fused[i]) > eps) {
            cout << "E" << i << " is used for ";
            cout << cplex.getValue(x[i]) << endl;
         }
      }
      cout << endl;
      cout << "----------------------------------------" << endl;
   }
   catch (IloException& ex) {
      cerr << "Error: " << ex << endl;
   }

   env.end();
   return 0;
}
示例#10
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;
}
void CPLEX_LP_IMSTSolver_v2::generateIncrementalConstraint(IncrementalParam k) {
	model.add(
			IloSum(edgeAddVariableArray) + IloSum(edgeDropVariableArray)
					<= 2 * IloNum(k));
}
示例#12
0
int main(int argc, const char* argv[]){
  IloEnv env;
  try{
    IloModel model(env);
    IloInt i, j;

    const char* filename = "../../../examples/data/facility.data";
    if (argc > 1)
      filename = argv[1];
    std::ifstream file(filename);
    if (!file){
      env.out() << "usage: " << argv[0] << " <file>" << std::endl;
      throw FileError();
    }

    IloIntArray capacity(env), fixedCost(env);
    IloArray<IloIntArray> cost(env);
    IloInt nbLocations;
    IloInt nbStores;

    file >> nbLocations;
    file >> nbStores;
    capacity = IloIntArray(env, nbLocations);
    for(i = 0; i < nbLocations; i++){
      file >> capacity[i];
    }
    fixedCost = IloIntArray(env, nbLocations);
    for(i = 0; i < nbLocations; i++){
      file >> fixedCost[i];
    }
    for(j = 0; j < nbStores; j++){
      cost.add(IloIntArray(env, nbLocations));
      for(i = 0; i < nbLocations; i++){
        file >> cost[j][i];
      }
    }

    IloBool consistentData = (fixedCost.getSize() == nbLocations);
    consistentData = consistentData && nbStores <= IloSum(capacity);
    for (i = 0; consistentData && (i < nbStores); i++)
      consistentData = (cost[i].getSize() == nbLocations);
    if (!consistentData){
      env.out() << "ERROR: data file '"
                << filename << "' contains inconsistent data" << std::endl;
    }

    IloIntVarArray supplier(env, nbStores, 0, nbLocations - 1);
    for (j = 0; j < nbLocations; j++)
      model.add(IloCount(supplier, j)  <= capacity[j]);
    model.add(supplier[2] != supplier[7]);
    IloIntVarArray open(env, nbLocations, 0, 1);
    for (i = 0; i < nbStores; i++)
      model.add(open[supplier[i]] == 1);

    IloIntExpr obj = IloScalProd(open, fixedCost);
    for (i = 0; i < nbStores; i++)
      obj += cost[i][supplier[i]];
    model.add(IloMinimize(env, obj));
    IloCP cp(model);
    cp.setParameter(IloCP::LogVerbosity, IloCP::Quiet);
    cp.solve();

    cp.out() << std::endl << "Optimal value: " << cp.getValue(obj) << std::endl;
    for (j = 0; j < nbLocations; j++){
      if (cp.getValue(open[j]) == 1){
        cp.out() << "Facility " << j << " is open, it serves stores ";
        for (i = 0; i < nbStores; i++){
          if (cp.getValue(supplier[i]) == j)
            cp.out() << i << " ";
        }
        cp.out() << std::endl;
      }
    }
  }
  catch(IloException& e){
    env.out() << " ERROR: " << e.getMessage() << std::endl;
  }
  env.end();
  return 0;
}
示例#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;
}
示例#14
0
int main(int, const char * []) {
  IloEnv env;
  try {
    IloModel model(env);
    IloInt m, o, c, q;

    IloInt         nbOrders   = 12;
    IloInt         nbSlabs    = 12;
    IloInt         nbColors   = 8;
    IloIntArray    capacities(env, 20, 0, 11, 13, 16, 17, 19, 20,
                                       23, 24, 25, 26, 27, 28, 29,
                                       30, 33, 34, 40, 43, 45);
    IloIntArray    sizes(env, nbOrders, 22, 9, 9, 8, 8, 6, 5, 3, 3, 3, 2, 2);
    IloIntArray    colors(env, nbOrders,  5, 3, 4, 5, 7, 3, 6, 0, 2, 3, 1, 5);
    IloIntVarArray where(env, nbOrders, 0, nbSlabs-1);
    IloIntVarArray load(env, nbSlabs, 0, IloSum(sizes));
  // Pack constraint
    model.add(IloPack(env, load, where, sizes));
  // Color constraints
    for(m = 0; m < nbSlabs; m++) {
      IloExprArray colorExpArray(env);
      for(c = 0; c < nbColors; c++) {
        IloOr orExp(env);
        for(o = 0; o < nbOrders; o++){
          if (colors[o] == c){
            orExp.add(where[o] == m);
          }
        }
        colorExpArray.add(orExp);
      }
      model.add(IloSum(colorExpArray) <= 2);
    }

  // Objective function
    IloIntArray lossValues(env);
    lossValues.add(0);
    for(q = 1; q < capacities.getSize(); q++){
      for(IloInt p = capacities[q-1] + 1; p <= capacities[q]; p++){
        lossValues.add(capacities[q] - p);
      }
    }
    IloExpr obj(env);
    for(m = 0; m < nbSlabs; m++){
      obj += lossValues[load[m]];
    }
    model.add(IloMinimize(env, obj));
    for(m = 1; m < nbSlabs; m++){
      model.add(load[m-1] >= load[m]);
    }
    IloCP cp(model);
    if (cp.solve(IloSearchPhase(env, where))){
      cp.out() << "Optimal value: " << cp.getValue(obj) << std::endl;
      for (m = 0; m < nbSlabs; m++) {
        IloInt p = 0;
        for (o = 0; o < nbOrders; o++)
          p += cp.getValue(where[o]) == m;
        if (p == 0) continue;
        cp.out() << "Slab " << m << " is used for order";
        if (p > 1) cp.out() << "s";
        cp.out() << " :";
        for (o = 0; o < nbOrders; o++) {
          if (cp.getValue(where[o]) == m)
            cp.out() << " " << o;
        }
        cp.out() << std::endl;
      }
    }
  }
  catch (IloException& ex) {
    env.out() << "Error: " << ex << std::endl;
  }
  env.end();
  return 0;
}
示例#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
示例#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