Exemplo n.º 1
0
/* initialisiere N^2 Variablen und erstelle eine zu minimierende
 * Strecken-Zielfunktion über die Distanzmatrix c
 *
 * eigentlich sind nur (N*N-N)/2 Variablen nötig, aber dafür müsste
 * ich mir etwas schlaues zur Adressierung ausdenken (weil das untere linke
 * Dreieck einer Matrix adressiert werden muss, ist das nicht trivial)
 * Der Presolver scheint die überflüssigen Variablen allerdings
 * direkt zu verwerfen, weshalb das nicht dringend ist.
 * */
IloNumVarArray CplexTSPSolver::init_symmetric_var(IloModel model)
{
    IloEnv env = model.getEnv();

    // Edge Variables
    IloNumVarArray x(env);
    for(int i=0; i<N; i++)
        for(int j=0; j<N; j++)
            if(j<i)
                x.add(IloNumVar(env, 0, 1, mip ? ILOINT : ILOFLOAT));
            else
                x.add(IloNumVar(env, 0, 0, ILOFLOAT)); // fülle oben rechts mit dummies
    model.add(x);

    // Cost Function
    IloExpr expr(env);

    // die folgenden Schleifen adressieren ein unteres linkes
    // Dreieck in einer quadratischen Matrix
    for(int i=0; i<N; i++)
        for (int j=0; j<i; j++)
            expr += c[i*N + j] * x[i*N + j];

    model.add(IloMinimize(env, expr));
    expr.end();

    return x;
}
Exemplo n.º 2
0
void MILPSolverCPX::addCol(const vector<pair<int,double> > & entries, const double & lb, const double & ub, const ColumnType & type)
{
    static const bool debug = false;
    
    if (debug) {
        cout << "Adding column to LP: ";
    }
 
    if (alwaysLPRelaxation) {
        (*modelvar).add(IloNumVar(*env, lb, ub));
    } else {
    
        if (type == C_BOOL) {
            (*modelvar).add(IloNumVar(*env, lb, ub, ILOBOOL));
            //cout << "Adding column " << colCount << " as binary\n";
            integervars.insert(make_pair(colCount, true));
        } else if (type == C_INT) {
            (*modelvar).add(IloNumVar(*env, lb, ub, ILOINT));
            //cout << "Adding column " << colCount << " as an integer\n";
            integervars.insert(make_pair(colCount, false));
        } else {
            (*modelvar).add(IloNumVar(*env, lb, ub));
        }
    }
        
    const int entCount = entries.size();
    for (int i = 0; i < entCount; ++i) {
        IloRange & target = modelcon->data[entries[i].first];
        target.setLinearCoef((*modelvar)[colCount], entries[i].second);
        coeffs[entries[i].first][colCount] = entries[i].second;
        if (debug) {
            if (i) cout << " + ";
            cout << entries[i].second << "*" << getRowName(entries[i].first);
        }

    }
    
            
    if (debug) {
        if (lb == -IloInfinity) {
            cout << " <= " << ub << "\n";
        } else if (ub == IloInfinity) {
            cout << " >= " << lb << "\n";
        } else if (ub == lb) {
            cout << " == " << ub << "\n";
        } else {
            cout << " in [" << lb << "," << ub << "]\n";            
        }
    }
                
    ++colCount;
}
Exemplo n.º 3
0
static void
populatebyrow (IloModel model, IloNumVarArray x, IloRangeArray c)
{
   IloEnv env = model.getEnv();

   x.add(IloNumVar(env, -1.0, 1.0));
   x.add(IloNumVar(env,  0.0, 1.0));
   model.add(IloMinimize(env, 0.5 * (-3*x[0]*x[0] - 3*x[1]*x[1] +
                                       - 1*x[0]*x[1]               ) ));

   c.add( - x[0] + x[1] >= 0);
   c.add(   x[0] + x[1] >= 0);
   model.add(c);
}  // END populatebyrow
Exemplo n.º 4
0
void profit_create_vars(graph g, IloModel model, IloNumVarArray x, IloNumVarArray p, IloNumVarArray z, int **columns) {
  IloEnv env = model.getEnv();
  string s;
  assignment_vars(g, model, x, columns);  
  for(int j = 0; j < g->items; j++) {
    s = "p_" + itos(j);
    p.add(IloNumVar(env, 0.0, boundp(j), ILOFLOAT, s.c_str()));
    // p.add(IloNumVar(env, lowerp(j), boundp(j), ILOFLOAT, s.c_str()));
  }
  for(int i = 0; i < g->bidders; i++) {
    s = "z_" + itos(i);
    z.add(IloNumVar(env, 0.0, boundu(i), ILOFLOAT, s.c_str()));
  }
}
int
main()
{
   IloEnv env;
   try {
      IloModel model(env);
    
      setData(env);
      IloNumVarArray  inside(env, nbProds);
      IloNumVarArray outside(env, nbProds);
   
      IloObjective obj = IloAdd(model, IloMinimize(env));
    
      // Must meet demand for each product
    
      for(IloInt p = 0; p < nbProds; p++) {
         IloRange demRange = IloAdd(model,
                                    IloRange (env, demand[p], demand[p]));
         inside[p]  = IloNumVar(obj(insideCost[p])  + demRange(1));
         outside[p] = IloNumVar(obj(outsideCost[p]) + demRange(1));
      }
    
      // Must respect capacity constraint for each resource
    
      for(IloInt r = 0; r < nbResources; r++)
         model.add(IloScalProd(consumption[r], inside) <= capacity[r]);
    
      IloCplex cplex(env);
      cplex.extract(model);
    
      cplex.solve();
    
      if (cplex.getStatus() != IloAlgorithm::Optimal)
         cout << "No optimal solution" << endl;
    
      cout << "Solution status: " << cplex.getStatus() << endl;
      displayResults(cplex, inside, outside);
      cout << "----------------------------------------" << endl;
   }
   catch (IloException& ex) {
      cerr << "Error: " << ex << endl;
   }
   catch (...) {
      cerr << "Error" << endl;
   }
   env.end();
   return 0;
}
Exemplo n.º 6
0
void addInitColumn(IloNumVarArray lambda, IloObjective rmpObj, 
	IloRangeArray maintConEng, IloRangeArray removeMod, IloRangeArray convex, 
	IloNumArray2 addXCol, IloNumArray addZCol, 
	const IloNumArray compCosts, const IloNumArray convexityCoef) {

	// loop counter
	IloInt t;		

	// counter for objective function coefficient for lambda
	// variable to be added.
	IloNum lambdaObjCoef = 0;

	// function assumes addXCol and addZCol contains proper values.

	// calculate objective function coefficient lambdaObjCoef
	for (t = 0; t < TIME_SPAN; t++) {

		// for each fixed t: scalar product of x[m]* vector and
		// component costs vector compCosts[m]:
		lambdaObjCoef += IloScalProd(addXCol[t],compCosts);

		// also clear the addXCol subarrays as soon as they
		// have been used
		addXCol[t].clear();
	}
			
	// now add this column and it's associated lambda variable to the RMP.
	lambda.add(IloNumVar(rmpObj(lambdaObjCoef) + maintConEng(addZCol) + 
		removeMod(addZCol) + convex(convexityCoef), 0.0, 1.0));

	// clear addZCol num array.
	addZCol.clear();

} // END of addColumn
Exemplo n.º 7
0
void addColumn(IloCplex subSolver, IloNumVarArray2 x, IloNumVarArray z, IloNumVarArray lambda,
	IloObjective rmpObj, IloRangeArray maintConEng, IloRangeArray removeMod,
	IloRangeArray convex, IloNumArray2 addXCol, IloNumArray addZCol, 
	const IloNumArray compCosts, const IloNumArray convexityCoef) {

	// loop counter
	IloInt t;		

	// counter for objective function coefficient for lambda
	// variable to be added.
	IloNum lambdaObjCoef = 0;

	// extract subproblem-optimal solution values
	// (into IloNumArrays addXCol (2d) and addZCol (1d)).

	// z values:
	subSolver.getValues(addZCol,z);

	//cout << endl << endl << "z = " << endl << addZCol << endl;
	//cin.get();

	// !!! OBS !!!
	// here we might want to save these z values some column pool's custom-nitted class
	// array. Or to be specific, we want to add the indexes for NON-ZERO-ENTRIES in addZCol
	// to our class that keep place of columns.
	// E.g., given variable lambda(m)_(q_m), we want to know in our own class object,
	// given (m)(q_m), the indexes of non-zeros in that Z column.
	


	// and for each t...
	for (t = 0; t < TIME_SPAN; t++) {

		// x values:
		subSolver.getValues(addXCol[t],x[t]);
		//cout << endl << endl << "x[t=" << t << "] =" << endl << addXCol[t] << endl;
	}
	//cin.get();

	// calculate objective function coefficient lambdaObjCoef
	for (t = 0; t < TIME_SPAN; t++) {

		// for each fixed t: scalar product of x[m]* vector and
		// component costs vector compCosts[m]:
		lambdaObjCoef += IloScalProd(addXCol[t],compCosts);

		// also clear the addXCol subarrays as soon as they
		// have been used
		addXCol[t].clear();
	}
			
	// now add this column and it's associated lambda variable to the RMP.
	lambda.add(IloNumVar(rmpObj(lambdaObjCoef) + maintConEng(addZCol) + 
		removeMod(addZCol) + convex(convexityCoef), 0.0, 1.0));

	// clear addZCol num array.
	addZCol.clear();

} // END of addColumn
Exemplo n.º 8
0
static void
populatebyrow (IloModel model, IloNumVarArray x, IloRangeArray c)
{
   IloEnv env = model.getEnv();

   x.add(IloNumVar(env, 0.0, 40.0));
   x.add(IloNumVar(env));
   x.add(IloNumVar(env));
   x.add(IloNumVar(env, 2.0, 3.0, ILOINT));
   model.add(IloMaximize(env, x[0] + 2 * x[1] + 3 * x[2] + x[3]));

   c.add( - x[0] +     x[1] + x[2] + 10 * x[3] <= 20);
   c.add(   x[0] - 3 * x[1] + x[2]             <= 30);
   c.add(              x[1]        - 3.5* x[3] == 0);
   model.add(c);

}  // END populatebyrow
Exemplo n.º 9
0
static void
populatebyrow (IloModel model, IloNumVarArray x, IloRangeArray c)
{
   IloEnv env = model.getEnv();

   x.add(IloNumVar(env, 0.0, 40.0));
   x.add(IloNumVar(env));
   x.add(IloNumVar(env));
   model.add(IloMaximize(env, x[0] + 2 * x[1] + 3 * x[2]
                            - 0.5 * (33*x[0]*x[0] + 22*x[1]*x[1] +
                                     11*x[2]*x[2] - 12*x[0]*x[1] -
                                     23*x[1]*x[2]                 ) ));

   c.add( - x[0] +     x[1] + x[2] <= 20);
   c.add(   x[0] - 3 * x[1] + x[2] <= 30);
   model.add(c);
}  // END populatebyrow
Exemplo n.º 10
0
void PopulateFromGraph(IloModel model, IloNumVarArray s, IloRangeArray c){
  IloEnv env = model.getEnv();

  // Used n+1 for accomodating an extra variable
  // For being able to write the objective function
  for(int i = 0; i <= n; i++)
    s.add(IloNumVar(env));
}
Exemplo n.º 11
0
void CPLEXSolver::add_in_constraint(LinearConstraint *con, double coef){
    DBG("Creating a Gurobi representation of a constriant %s\n", "");
    IloNumArray weights(*env, (IloInt)con->_coefficients.size());
    IloNumVarArray vars(*env, (IloInt)con->_variables.size());
    
    for(unsigned int i = 0; i < con->_variables.size(); ++i){
        DBG("\tAdding variable to CPLEX\n%s", "");
        IloNumVar var_ptr;
        
        if(con->_variables[i]->_var == NULL){
            
            IloNumVar::Type type;
        
            if(con->_variables[i]->_continuous) type = IloNumVar::Float;
            // else if(con->_lower == 0 && con->_upper == 1) type = IloNumVar::Bool;
            else type = IloNumVar::Int;

            var_ptr = IloNumVar(getEnv(),
                                con->_variables[i]->_lower, // LB
                                con->_variables[i]->_upper, // UB
                                type);

            int *var_id = new int;
            *var_id = variables->getSize();
            variables->add(var_ptr);
            con->_variables[i]->_var = (void*) var_id;
            
            DBG("Created new variable with id %d. type:%c lb:%f ub:%f coef:%f\n", *var_id, type, con->_variables[i]->_lower, con->_variables[i]->_upper, coef);
        } else {
            var_ptr = (*variables)[*(int*)(con->_variables[i]->_var)];
        }

        vars[i] = (*variables)[*(int*)(con->_variables[i]->_var)];
        weights[i] = con->_coefficients[i];
    }

    IloNumExprArg lin_expr = IloScalProd(weights, vars);

    if(coef < -0.1){
        model->add(IloMinimize(*env, lin_expr));
    } else if(coef > 0.1){
        model->add(IloMaximize(*env, lin_expr));
    } else {
        if(con->_lhs > -INFINITY && con->_rhs < INFINITY){
            if(con->_lhs == con->_rhs) {
                model->add(lin_expr == con->_lhs);
            } else {
                model->add(IloRange(*env, con->_lhs, lin_expr, con->_rhs));
            }
        } else if(con->_lhs > -INFINITY) model->add(lin_expr >= con->_lhs);
        else if(con->_rhs < INFINITY) model->add(lin_expr <= con->_rhs);
    }
}
Exemplo n.º 12
0
static void
populatebyrow (IloModel model, IloNumVarArray x, IloRangeArray c)
{
   IloEnv env = model.getEnv();

   x.add(IloNumVar(env, 0.0, 40.0));
   x.add(IloNumVar(env, 0.0, IloInfinity, ILOINT));
   x.add(IloNumVar(env, 0.0, IloInfinity, ILOINT));
   x.add(IloNumVar(env, 2.0, 3.0, ILOINT));
   model.add(IloMaximize(env, x[0] + 2 * x[1] + 3 * x[2] + x[3]));

   c.add( - x[0] +     x[1] + x[2] + 10 * x[3] <= 20);
   c.add(   x[0] - 3 * x[1] + x[2]             <= 30);
   c.add(              x[1]        - 3.5* x[3] == 0);
   model.add(c);

   IloNumVarArray sosvar(env, 2);
   IloNumArray    sosval(env, 2);
   sosvar[0] = x[2]; sosvar[1] = x[3];
   sosval[0] = 25.0; sosval[1] = 18.0;

   model.add(IloSOS1(model.getEnv(), sosvar, sosval));

}  // END populatebyrow
Exemplo n.º 13
0
static void
populatebycolumn (IloModel model, IloNumVarArray x, IloRangeArray c)
{
   IloEnv env = model.getEnv();

   IloObjective obj = IloMaximize(env);
   c.add(IloRange(env, -IloInfinity, 20.0));
   c.add(IloRange(env, -IloInfinity, 30.0));

   x.add(IloNumVar(obj(1.0) + c[0](-1.0) + c[1]( 1.0), 0.0, 40.0));
   x.add(obj(2.0) + c[0]( 1.0) + c[1](-3.0));
   x.add(obj(3.0) + c[0]( 1.0) + c[1]( 1.0));

   model.add(obj);
   model.add(c);
}  // END populatebycolumn
Exemplo n.º 14
0
bool MIQPSolver::addContig(const Contig &contig)
{
	int id = contig.GetID();
	try
	{
		len[id] = contig.Sequence.Nucleotides.length();
		optimized[id] = false;
		x.add(IloNumVar(environment, 0, CoordMax));
		u.add(IloBoolVar(environment));
		t.add(IloBoolVar(environment));
		constraints.add(t[id] - u[id] <= 0);
	}
	catch (...)
	{
		return false;
	}
	return true;
}
Exemplo n.º 15
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;
}
Exemplo n.º 16
0
int CProblem::setModel()
{
	//time_t start, end;

	IloEnv env;
	try
	{
		IloModel model(env);
		IloCplex cplex(env);

		/*Variables*/
		IloNumVar lambda(env, "lambda");
		IloNumVarArray c(env, n); //
		for (unsigned int u = 0; u < n; u++)
		{
			std::stringstream ss;
			ss << u;
			std::string str = "c" + ss.str();
			c[u] = IloNumVar(env, str.c_str());
		}

		IloIntVarArray z0(env, Info.numAddVar);
		for (int i = 0; i < Info.numAddVar; i++)
		{
			std::stringstream ss;
			ss << i;
			std::string str = "z0_" + ss.str();
			z0[i] = IloIntVar(env, 0, 1, str.c_str());
		}

		/*  Objective*/
		model.add(IloMinimize(env, lambda));
		/*Constrains*/
		/* d=function of the distance */
		IloArray<IloNumArray> Par_d(env, n);
		for (unsigned int u = 0; u < n; u++)
		{
			Par_d[u] = IloNumArray(env, n);
			for (unsigned int v = 0; v < n; v++)
			{
				Par_d[u][v] = d[u][v];
			}
		}

		int M = (max_distance + 1) * n;
		for (int i = 0; i < Info.numAddVar; i++)
		{
			int u = Info.ConstrIndex[i * 2];
			int v = Info.ConstrIndex[i * 2 + 1];

			model.add(c[u] - c[v] + M * (z0[i]) >= Par_d[u][v]);
			model.add(c[v] - c[u] + M * (1 - z0[i]) >= Par_d[u][v]);

		}

		
		// d(x) = 3 - x
		if (max_distance == 2) 
		{ 
		  // Gridgraphen 1x2 (6 Knoten) 
		  for (int i = 0; i < sqrt(n)-1; i+=1)
		  {
		    for (int j = 0; j < sqrt(n)-2; j+=2)
		    {
			  model.add(c[i * sqrt(n) + j] + c[i * sqrt(n) + j+2] +
			  c[(i+1) * sqrt(n) + j] + c[(i+1) * sqrt(n) + j+2] >= 16.2273);
		    }
		  }
		  
		  
		  //
		}
		
		//d(x) = 4 - x
		
		if (max_distance == 3) 
		{
		 
		  // Gridgraphen 1x2 (6 Knoten) 
		  for (int i = 0; i < sqrt(n)-1; i+=1)
		  {
		    for (int j = 0; j < sqrt(n)-2; j+=2)
		    {
			  model.add(c[i * sqrt(n) + j] + c[i * sqrt(n) + j+2] +
			  c[(i+1) * sqrt(n) + j] + c[(i+1) * sqrt(n) + j+2] >= 30.283);
		    }
		  }
		  
		  
		}
		
		

		for (unsigned int v = 0; v < n; v++)
		{
			model.add(c[v] <= lambda);
			model.add(c[v] >= 0);
		}

		std::cout << "Number of variables " << Info.numVar << "\n";

		/* solve the Model*/
		cplex.extract(model);
		cplex.exportModel("L-Labeling.lp");

		IloTimer timer(env);
		timer.start();
		int solveError = cplex.solve();
		timer.stop();

		if (!solveError)
		{
			std::cout << "STATUS : " << cplex.getStatus() << "\n";
			env.error() << "Failed to optimize LP \n";
			exit(1);
		}
		//Info.time = (double)(end-start)/(double)CLOCKS_PER_SEC;
		Info.time = timer.getTime();

		std::cout << "STATUS : " << cplex.getStatus() << "\n";
		/* get the solution*/
		env.out() << "Solution status = " << cplex.getStatus() << "\n";
		Info.numConstr = cplex.getNrows();
		env.out() << " Number of constraints = " << Info.numConstr << "\n";
		lambda_G_d = cplex.getObjValue();
		env.out() << "Solution value  = " << lambda_G_d << "\n";
		for (unsigned int u = 0; u < n; u++)
		{
			C.push_back(cplex.getValue(c[u]));
			std::cout << "c(" << u << ")=" << C[u] << " ";
		}

	} // end try
	catch (IloException& e)
	{
		std::cerr << "Concert exception caught: " << e << std::endl;
	} catch (...)
	{
		std::cerr << "Unknown exception caught" << std::endl;
	}
	env.end();
	return 0;
}
Exemplo n.º 17
0
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();
		}
	}
}
Exemplo n.º 18
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;
}
Exemplo n.º 19
0
int CProblem::setModel() {
	//time_t start, end;

	numvar = 1+n; // lambda + all c;

	IloEnv  env;
	try {
		IloModel model(env);
		IloCplex cplex(env);

		/*Variables*/
		IloNumVar lambda(env, "lambda");
		IloNumVarArray c(env, n);//
		for (unsigned int u=0; u<n; u++) {
			std::stringstream ss;
			ss << u;
			std::string str = "c" + ss.str();
			c[u]=IloNumVar(env, str.c_str());
		}

		IloArray<IloIntVarArray> z(env,n);
		for (unsigned int u=0; u<n; u++) {
			z[u]= IloIntVarArray(env, n);
			for (unsigned int v=0; v<n; v++) {
				std::stringstream ss;
				ss << u;
				ss << v;
				std::string str = "z" + ss.str();
				z[u][v] = IloIntVar(env, 0, 1, str.c_str());
			}
		}

		/* Constant M*/
		int M=n*max_d;
		UB = M;

		/*  Objective*/
		model.add(IloMinimize(env, lambda));

		/*Constrains*/
		model.add(lambda - UB <= 0);

		/* d=function of the distance */
		IloArray<IloNumArray> Par_d(env,n);
		for (unsigned int u=0; u<n; u++) {
			Par_d[u]=IloNumArray(env,n);
			for (unsigned int v=0; v<n; v++) {
				Par_d[u][v]=d[u][v];
			}
		}

		for (unsigned u=0; u<n; u++) {
			for (unsigned v=0; v<u; v++) {
				model.add(c[v]-c[u]+M*   z[u][v]  >= Par_d[u][v] );
				model.add(c[u]-c[v]+M*(1-z[u][v]) >= Par_d[u][v]);
				numvar++; // + z[u][v]
			}
		}


		for (unsigned int v=0; v<n; v++) {
			IloExpr expr;
			model.add (c[v] <= lambda);
			model.add (c[v] >= 0);
			expr.end();
		}



		std::cout << "Number of variables " << numvar << "\n";

		/* solve the Model*/
		cplex.extract(model);
		cplex.exportModel("L-Labeling.lp");

		/*
		start = clock();
		int solveError = cplex.solve();
		end = clock ();
		*/

//		cplex.setParam(IloCplex::Threads, 1);
		cplex.setParam(IloCplex::ClockType , 1 ); // CPU time
	      
		IloTimer timer(env);
		const double startt =  cplex.getTime();
		timer.start();
		int solveError = cplex.solve();
		timer.stop();
		const double stopt = cplex.getTime() - startt;

		if ( !solveError ) {
			std::cout << "STATUS : "<< cplex.getStatus() << "\n";
			env.error() << "Failed to optimize LP \n";
			exit(1);
		}
		//Info.time = (double)(end-start)/(double)CLOCKS_PER_SEC;
		Info.time = timer.getTime();

		std::cout << "STATUS : "<< cplex.getStatus() << "\n";
		/* get the solution*/
		env.out() << "Solution status = " << cplex.getStatus() << "\n";
		env.out() << "Time cplex.getTime " << stopt << "\n";
		numconst = cplex.getNrows();
		env.out() << " Number of constraints = " << numconst << "\n";
		lambda_G_d=cplex.getObjValue();
		env.out() << "Solution value  = " << lambda_G_d << "\n";
		for (unsigned int u=0; u<n; u++) {
			C.push_back(cplex.getValue(c[u]));
			std::cout << "c(" << u << ")=" << C[u]<< " ";
		}
		std::cout <<"\n";
		/*
		for (unsigned int u=0; u<n; u++) {
			for (unsigned int v=0; v<u; v++) {
				std::cout<< "z[" << u <<"][" << v << "]="<< cplex.getValue( z[u][v]) << " ";
				Z.push_back(cplex.getValue( z[u][v]));
			}
			std::cout << "\n";
		}
		std::cout <<"\n";
		 */
	}	// end try
	catch (IloException& e) {
		std::cerr << "Concert exception caught: " << e << std::endl;
	}
	catch (...) {
		std::cerr << "Unknown exception caught" << std::endl;
	}
	env.end();
	return 0;
}
Exemplo n.º 20
0
int  main (int argc, char *argv[])
{ 
     ifstream infile;
     
     infile.open("Proj3_op.txt");
     if(!infile){
	cerr << "Unable to open the file\n";
	exit(1);
     }
     
     cout << "Before Everything!!!" << "\n";
     IloEnv env;
     IloInt   i,j,varCount1,varCount2,varCount3,conCount;                                                    //same as “int i;”
     IloInt k,w,K,W,E,l,P,N,L;
     IloInt tab, newline, val; //from file
     char line[2048];
     try {
	N = 9;
	K = 3;
	L = 36;
	W = (IloInt)atoi(argv[1]);
        IloModel model(env);		//set up a model object

	IloNumVarArray var1(env);// C - primary
	cout << "Here\n";
	IloNumVarArray var2(env);// B - backup
	cout << "here1\n";
	IloNumVarArray var3(env);// = IloNumVarArray(env,W);		//declare an array of variable objects, for unknowns 
	IloNumVar W_max(env, 0, W, ILOINT);
	//var1: c_ijk_w
	IloRangeArray con(env);// = IloRangeArray(env,N*N + 3*w);		//declare an array of constraint objects
        IloNumArray2 t = IloNumArray2(env,N); //Traffic Demand
        IloNumArray2 e = IloNumArray2(env,N); //edge matrix
        //IloObjective obj;

	//Define the Xijk matrix
	cout << "Before init xijkl\n";
     	Xijkl xijkl_m(env, L);
        for(l=0;l<L;l++){
                xijkl_m[l] = Xijk(env, N);
                for(i=0;i<N;i++){
                        xijkl_m[l][i] = Xjk(env, N);
                        for(j=0;j<N;j++){
                                xijkl_m[l][i][j] = IloNumArray(env, K);
                        }
                }
        }


	
	//reset everything to zero here
	for(l=0;l<L;l++)
                for(i=0;i<N;i++)
                        for(j=0;j<N;j++)
                                for(k=0;k<K;k++)
                                        xijkl_m[l][i][j][k] = 0;

	input_Xijkl(xijkl_m);


	
	cout<<"bahre\n";
	
	for(i=0;i<N;i++){
		t[i] = IloNumArray(env,N);
		for(j=0;j<N;j++){
			if(i == j)
				t[i][j] = IloNum(0);
			else if(i != j)
				t[i][j] = IloNum((i+j+2)%5);
		}
	}
	
	printf("ikde\n");
	//Minimize W_max
        IloObjective obj=IloMinimize(env);
	obj.setLinearCoef(W_max, 1.0);

	cout << "here khali\n"; 
	//Setting var1[] for Demands Constraints
	for(i=0;i<N;i++)
		for(j=0;j<N;j++)
			for(k=0;k<K;k++)
				for(w=0;w<W;w++)
					var1.add(IloNumVar(env, 0, 1, ILOINT));
	//c_ijk_w variables set.

	//Setting var2[] for Demands Constraints
        for(i=0;i<N;i++)
                for(j=0;j<N;j++)
                        for(k=0;k<K;k++)
                                for(w=0;w<W;w++)
                                        var2.add(IloNumVar(env, 0, 1, ILOINT));
        //b_ijk_w variables set.



	for(w = 0;w < W;w++)
		var3.add(IloNumVar(env, 0, 1, ILOINT)); //Variables for u_w
	cout<<"variables ready\n";
	conCount = 0;
	for(i=0;i<N;i++)
		for(j=0;j<N;j++){
			con.add(IloRange(env, 2 * t[i][j], 2 * t[i][j]));
			//varCount1 = 0;
			for(k=0;k<K;k++)
				for(w=0;w<W;w++){
					con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0);
					con[conCount].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w],1.0);
				}
			conCount++;
		}//Adding Demands Constraints to con
	cout<<"1st\n";

	IloInt z= 0;
        for(w=0;w<W;w++){
                for(l=0;l<L;l++){
                        con.add(IloRange(env, -IloInfinity, 1));
                        for(i=0;i<N;i++){
                                for(j=0;j<N;j++){
                                        for(k=0;k<K;k++){
                                                con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],xijkl_m[l][i][j][k]);
						con[conCount].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w],xijkl_m[l][i][j][k]);
                                        }
                                }
                        }
                        conCount++;
                }
        }


	cout<<"2nd\n";

	//Adding Wavelength Constraints_1 to con
	P = N * (N-1) * K;	
	for(w=0;w<W;w++){
		con.add(IloRange(env, -IloInfinity, 0));
		varCount1 = 0;
                for(i=0;i<N;i++)
                       for(j=0;j<N;j++)
                               for(k=0;k<K;k++){
					con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0);
					con[conCount].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w],1.0);
                               }
		con[conCount].setLinearCoef(var3[w],-P);
                conCount++;

	}
	cout<<"3rd\n";
	

	for(i=0;i<N;i++)
                       for(j=0;j<N;j++)
                               for(k=0;k<K;k++)
					for(w=0;w<W;w++){
						con.add(IloRange(env, -IloInfinity, 1));
						con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w], 1.0);
						con[conCount++].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w], 1.0);
						
					}


	varCount3 = 0;
	for(w=0;w<W;w++){
                con.add(IloRange(env, 0, IloInfinity));
                con[conCount].setLinearCoef(W_max, 1.0);
                con[conCount++].setLinearCoef(var3[w], -1.0 * (w+1));
        }
	cout<<"after constraints\n";

	
	//model.add(obj);			//add objective function into model
        model.add(IloMinimize(env,obj));
	model.add(con);			//add constraints into model
        IloCplex cplex(model);			//create a cplex object and extract the 					//model to this cplex object
        // Optimize the problem and obtain solution.
        if ( !cplex.solve() ) {
           env.error() << "Failed to optimize LP" << endl;
           throw(-1);
        }
        IloNumArray vals(env);		//declare an array to store the outputs
				 //if 2 dimensional: IloNumArray2 vals(env);
        env.out() << "Solution status = " << cplex.getStatus() << endl;
		//return the status: Feasible/Optimal/Infeasible/Unbounded/Error/…
        env.out() << "Solution value  = " << cplex.getObjValue() << endl; 
		//return the optimal value for objective function
	cplex.getValues(vals, var1);                    //get the variable outputs
        env.out() << "Values Var1        = " <<  vals << endl;  //env.out() : output stream
        cplex.getValues(vals, var3);
        env.out() << "Values Val3        = " <<  vals << endl;

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

     return 0;
  }  // END main
Exemplo n.º 21
0
MILPSolverCPX::MILPSolverCPX(MILPSolverCPX & c)
{
    static const bool debug = false;
    
    if (debug) {
        cout << "Copying...\n";
        ostringstream copyfn;
        copyfn << "copyconstructor" << *(c.envUsers) << ".lp";
        const string copyfns = copyfn.str();
        c.writeLp(copyfns.c_str());
    }
        
    env = c.env;
    envUsers = c.envUsers;
    ++(*envUsers);
    
    model = new IloModel(*env);
    
    modelvar = new IloNumVarArray(*env);
    modelcon = new Constraints();   
    
    obj = new IloObjective(*env);
    obj->setSense(IloObjective::Minimize);
    
    model->add(*obj);

    
    colCount = c.colCount;
    rowCount = c.rowCount;

    integervars = c.integervars;   

    map<int,bool>::const_iterator iItr = integervars.begin();
    const map<int,bool>::const_iterator iEnd = integervars.end();
        
    for (int ci = 0; ci < colCount; ++ci) {
        const double lb = (*(c.modelvar))[ci].getLB();
        const double ub = (*(c.modelvar))[ci].getUB();
        
        if (iItr != iEnd && iItr->first == ci) {
            modelvar->add(IloNumVar(*env, lb, ub, (iItr->second ? ILOBOOL : ILOINT)));
            //cout << "Column " << ci << " in the copy is an integer\n";
            ++iItr;
        } else {        
            modelvar->add(IloNumVar(*env, lb, ub));
        }
        const char * oldName = (*(c.modelvar))[ci].getName();
        (*modelvar)[ci].setName(oldName);
       
    }
    
    coeffs = c.coeffs;
    
    map<int,map<int,double> >::const_iterator coItr = coeffs.begin();
    const map<int,map<int,double> >::const_iterator coEnd = coeffs.end();
    
    map<int,IloRange>::iterator dItr = c.modelcon->data.begin();
    const map<int,IloRange>::iterator dEnd = c.modelcon->data.end();
    
    for (int r = 0; dItr != dEnd; ++r, ++dItr) {
        const double lb = dItr->second.getLB();
        const double ub = dItr->second.getUB();
        
        IloRange & newRange = modelcon->data[r] = IloAdd(*model, IloRange(*env, lb,ub));
        
       
        if (dItr->second.getName()) {
            newRange.setName(dItr->second.getName());
        }
        
        if (coItr == coEnd) continue;
        if (r < coItr->first) continue;
        
        map<int,double>::const_iterator fItr = coItr->second.begin();
        const map<int,double>::const_iterator fEnd = coItr->second.end();
        
        for (; fItr != fEnd; ++fItr) {
            newRange.setLinearCoef((*modelvar)[fItr->first], fItr->second);
        }
        ++coItr;
    }
    
    
    
    cplex = new IloCplex(*model);
    setILS(cplex);
    
    solArray = 0;
    
    if (debug) {
        ostringstream copyfn;
        copyfn << "aftercopyconstructor" << *(c.envUsers) << ".lp";
        const string copyfns = copyfn.str();
        
        writeLp(copyfns.c_str());
    }
}
Exemplo n.º 22
0
int CProblem::setModel() {
	//time_t start, end;

	numvar = 1+n; // lambda + all c;

	IloEnv  env;
	try {
		IloModel model(env);
		IloCplex cplex(env);

		/*Variables*/
		IloNumVar lambda(env, "lambda");
		IloNumVarArray c(env, n);//
		for (unsigned int u=0; u<n; u++) {
			std::stringstream ss;
			ss << u;
			std::string str = "c" + ss.str();
			c[u]=IloNumVar(env, str.c_str());
		}

		IloArray<IloIntVarArray> z(env,n);
		for (unsigned int u=0; u<n; u++) {
			z[u]= IloIntVarArray(env, n);
			for (unsigned int v=0; v<n; v++) {
				std::stringstream ss;
				ss << u;
				ss << v;
				std::string str = "z" + ss.str();
				z[u][v] = IloIntVar(env, 0, 1, str.c_str());
			}
		}

		/* Constant M*/
		int UB, LB;
		switch (lattice){
		  case 1: // hexagonal_lattice 
		    if (max_d==3) {LB = 5; UB = 10;}	//d(x) = 3 -x
		    else {LB = 9; UB = 27;}
		    
		    break;
		  case 2:// triangular_lattice
		    if (max_d==3) { LB = 8; UB = 16;}	//d(x) = 3 -x
		    else {LB = 18; UB = 54;}
		    break;
		  case 3:// square_lattice
		    if (max_d==3) { LB = 6; UB = 12;}	//d(x) = 3 -x
		    else { LB = 11; UB = 33;}
		    break;
		  default: UB=n*max_d;break;
		}
		std::cout << "Lattice " << lattice << "\n";
		std::cout << "UB for lambda " << UB << "\n";

		/*  Objective*/
		model.add(IloMinimize(env, lambda));

		/*Constrains*/
		model.add(lambda - UB <= 0);
		model.add(lambda - LB >= 0);
		
		/* d=function of the distance */
		IloArray<IloNumArray> Par_d(env,n);
		for (unsigned int u=0; u<n; u++) {
			Par_d[u]=IloNumArray(env,n);
			for (unsigned int v=0; v<n; v++) {
				Par_d[u][v]=d[u][v];
			}
		}
		
		int M = INT_MAX;//Par_d[0][0] + UB;
		for (unsigned u=0; u<n; u++) {
			for (unsigned v=0; v<u; v++) {
				model.add(c[v]-c[u]+M*   z[u][v]  >= Par_d[u][v] );
				model.add(c[u]-c[v]+M*(1-z[u][v]) >= Par_d[u][v]);
				numvar++; // + z[u][v]
			}
		}

		for (unsigned int v=0; v<n; v++) {
			IloExpr expr;
			model.add (c[v] <= lambda);
			model.add (c[v] >= 0);
			expr.end();
		}



		std::cout << "Number of variables " << numvar << "\n";

		/* solve the Model*/
		cplex.extract(model);
		cplex.exportModel("L-Labeling.lp");

		IloTimer timer(env);
		timer.start();
		int solveError = cplex.solve();
		timer.stop();

		if ( !solveError ) {
			std::cout << "STATUS : "<< cplex.getStatus() << "\n";
			env.error() << "Failed to optimize LP \n";
			exit(1);
		}
		//Info.time = (double)(end-start)/(double)CLOCKS_PER_SEC;
		Info.time = timer.getTime();

		std::cout << "STATUS : "<< cplex.getStatus() << "\n";
		/* get the solution*/
		env.out() << "Solution status = " << cplex.getStatus() << "\n";
		numconst = cplex.getNrows();
		env.out() << " Number of constraints = " << numconst << "\n";
		lambda_G_d=cplex.getObjValue();
		env.out() << "Solution value  = " << lambda_G_d << "\n";
		for (unsigned int u=0; u<n; u++) {
			C.push_back(cplex.getValue(c[u]));
			std::cout << "c(" << u << ")=" << C[u]<< " ";
		}
		std::cout <<"\n";
		/*
		for (unsigned int u=0; u<n; u++) {
			for (unsigned int v=0; v<u; v++) {
				std::cout<< "z[" << u <<"][" << v << "]="<< cplex.getValue( z[u][v]) << " ";
				Z.push_back(cplex.getValue( z[u][v]));
			}
			std::cout << "\n";
		}
		std::cout <<"\n";
		 */
	}	// end try
	catch (IloException& e) {
		std::cerr << "Concert exception caught: " << e << std::endl;
	}
	catch (...) {
		std::cerr << "Unknown exception caught" << std::endl;
	}
	env.end();
	return 0;
}
Exemplo n.º 23
0
int  main (int argc, char *argv[])
{ 
     ifstream infile;
     clock_t start_time, end_time;
     infile.open("Proj3_op.txt");
     if(!infile){
	cerr << "Unable to open the file\n";
	exit(1);
     }
     
     cout << "Before Everything!!!" << "\n";
     IloEnv env;
     IloInt   i,j,varCount1,varCount2,varCount3,conCount;                                                    //same as “int i;”
     IloInt k,w,K,W,E,l,P,N,L;
     IloInt tab, newline, val; //from file
     char line[2048];
     try {
	N = 9;
	K = 2;
	L = 36;
	W = (IloInt)atoi(argv[1]);
        IloModel model(env);		//set up a model object

	IloNumVarArray var1(env);// = IloNumVarArray(env,K*W*N*N);
	IloNumVarArray var3(env);// = IloNumVarArray(env,W);		//declare an array of variable objects, for unknowns 
	IloNumVar W_max(env, 0, W, ILOINT);
	IloRangeArray con(env);// = IloRangeArray(env,N*N + 3*w);		//declare an array of constraint objects
        IloNumArray2 t = IloNumArray2(env,N); //Traffic Demand
        IloNumArray2 e = IloNumArray2(env,N); //edge matrix
        //IloObjective obj;

	//Define the Xijk matrix
     	Xijkl xijkl_m(env, L);
        for(l=0;l<L;l++){
                xijkl_m[l] = Xijk(env, N);
                for(i=0;i<N;i++){
                        xijkl_m[l][i] = Xjk(env, N);
                        for(j=0;j<N;j++){
                                xijkl_m[l][i][j] = IloNumArray(env, K);
                        }
                }
        }


	
	//reset everything to zero here
	for(l=0;l<L;l++)
                for(i=0;i<N;i++)
                        for(j=0;j<N;j++)
                                for(k=0;k<K;k++)
                                        xijkl_m[l][i][j][k] = 0;

	input_Xijkl(xijkl_m);


	
	cout<<"bahre\n";
	FILE *file;
	file = fopen(argv[2],"r");
	int tj[10];
	for(i=0;i<N;i++){
		t[i] = IloNumArray(env,N);
		fscanf(file,"%d %d %d %d %d %d %d %d %d \n",&tj[0],&tj[1],&tj[2],&tj[3],&tj[4],&tj[5],&tj[6],&tj[7],&tj[8]);
		
		for(j=0;j<N;j++){
			t[i][j] = IloNum(tj[j]);
		}
	}
	


	printf("ikde\n");
	//Minimize W_max
        IloObjective obj=IloMinimize(env);
	obj.setLinearCoef(W_max, 1.0);

	cout << "here khali\n"; 
	//Setting var1[] for Demands Constraints
	for(i=0;i<N;i++)
		for(j=0;j<N;j++)
			for(k=0;k<K;k++)
				for(w=0;w<W;w++)
					var1.add(IloNumVar(env, 0, 1, ILOINT));


	for(w = 0;w < W;w++)
		var3.add(IloNumVar(env, 0, 1, ILOINT)); //Variables for u_w
	cout<<"variables ready\n";
	conCount = 0;
	for(i=0;i<N;i++)
		for(j=0;j<N;j++){
			con.add(IloRange(env, t[i][j], t[i][j]));
			//varCount1 = 0;
			for(k=0;k<K;k++)
				for(w=0;w<W;w++){
					con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0);
					//cout << "Before Adding Constraint\n";
					//con[1].setLinearCoef(IloNumVar(env, 0, 1, ILOINT), 1.0);
					//cout<<"coef set "<<varCount1;
				}
			conCount++;
		}//Adding Demands Constraints to con
	cout<<"1st\n";

	IloInt z= 0;
        for(w=0;w<W;w++){
                for(l=0;l<L;l++){
                        con.add(IloRange(env, -IloInfinity, 1));
                        for(i=0;i<N;i++){
                                for(j=0;j<N;j++){
                                        for(k=0;k<K;k++){
                                                con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],xijkl_m[l][i][j][k]);
                                        }
                                }
                        }
                        conCount++;
                }
        }


	cout<<"2nd\n";

	//Adding Wavelength Constraints_1 to con
	P = N * (N-1) * K;	
	for(w=0;w<W;w++){
		con.add(IloRange(env, -IloInfinity, 0));
		varCount1 = 0;
                for(i=0;i<9;i++)
                       for(j=0;j<9;j++)
                               for(k=0;k<K;k++){
					con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0);
                               }
		con[conCount].setLinearCoef(var3[w],-P);
                conCount++;

	}
	cout<<"3rd\n";
	
	varCount3 = 0;
	for(w=0;w<W;w++){
		con.add(IloRange(env, 0, IloInfinity));
		con[conCount].setLinearCoef(W_max, 1.0);
 		con[conCount++].setLinearCoef(var3[w], -1.0 * (w+1));
	}
	cout<<"after constraints\n";

	
	//model.add(obj);			//add objective function into model
        model.add(IloMinimize(env,obj));
	model.add(con);			//add constraints into model
        IloCplex cplex(model);			//create a cplex object and extract the 					//model to this cplex object
        // Optimize the problem and obtain solution.
	start_time = clock();
        if ( !cplex.solve() ) {
           env.error() << "Failed to optimize LP" << endl;
           throw(-1);
        }
	end_time = clock();
        IloNumArray vals(env);		//declare an array to store the outputs
	IloNumVarArray opvars(env);			 //if 2 dimensional: IloNumArray2 vals(env);
        //env.out() << "Solution status = " << cplex.getStatus() << endl;
		//return the status: Feasible/Optimal/Infeasible/Unbounded/Error/…
        env.out() << "W_max value  = " << cplex.getObjValue() << endl; 
		//return the optimal value for objective function
        cplex.getValues(vals, var1);			//get the variable outputs
        //env.out() << "Values Var1        = " <<  vals << endl;	//env.out() : output stream
	cplex.getValues(vals, var3);
	//env.out() << "Values Val3        = " <<  vals << endl; 

     }
     catch (IloException& e) {
        cerr << "Concert exception caught: " << e << endl;
     }
     catch (...) {
        cerr << "Unknown exception caught" << endl;
     }
  
     env.end();				//close the CPLEX environment
     float running_time (((float)end_time - (float)start_time)/CLOCKS_PER_SEC);
     cout << "*******RUNNING TIME: " << running_time << endl;
     return 0;
  }  // END main
Exemplo n.º 24
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
Exemplo n.º 25
0
int
main(int argc, char **argv)
{
   IloEnv env;
   try {
      IloInt  i, j;

      IloNum      rollWidth;
      IloNumArray amount(env);
      IloNumArray size(env);

      if ( argc > 1 )
         readData(argv[1], rollWidth, size, amount);
      else
         readData("../../../examples/data/cutstock.dat",
                  rollWidth, size, amount);

      /// CUTTING-OPTIMIZATION PROBLEM ///

      IloModel cutOpt (env);

      IloObjective   RollsUsed = IloAdd(cutOpt, IloMinimize(env));
      IloRangeArray  Fill = IloAdd(cutOpt,
                                   IloRangeArray(env, amount, IloInfinity));
      IloNumVarArray Cut(env);

      IloInt nWdth = size.getSize();
      for (j = 0; j < nWdth; j++) {
         Cut.add(IloNumVar(RollsUsed(1) + Fill[j](int(rollWidth / size[j]))));
      }
      
      IloCplex cutSolver(cutOpt);

      /// PATTERN-GENERATION PROBLEM ///

      IloModel patGen (env);

      IloObjective ReducedCost = IloAdd(patGen, IloMinimize(env, 1));
      IloNumVarArray Use(env, nWdth, 0.0, IloInfinity, ILOINT);
      patGen.add(IloScalProd(size, Use) <= rollWidth);

      IloCplex patSolver(patGen);

      /// COLUMN-GENERATION PROCEDURE ///

      IloNumArray price(env, nWdth);
      IloNumArray newPatt(env, nWdth);

      /// COLUMN-GENERATION PROCEDURE ///

      for (;;) {
         /// OPTIMIZE OVER CURRENT PATTERNS ///
       
         cutSolver.solve();
         report1 (cutSolver, Cut, Fill);
       
         /// FIND AND ADD A NEW PATTERN ///
       
         for (i = 0; i < nWdth; i++) {
           price[i] = -cutSolver.getDual(Fill[i]);
         }
         ReducedCost.setLinearCoefs(Use, price);
       
         patSolver.solve();
         report2 (patSolver, Use, ReducedCost);
       
         if (patSolver.getValue(ReducedCost) > -RC_EPS) break;
       
         patSolver.getValues(newPatt, Use);
         Cut.add( IloNumVar(RollsUsed(1) + Fill(newPatt)) );
      }

      cutOpt.add(IloConversion(env, Cut, ILOINT));

      cutSolver.solve();
      cout << "Solution status: " << cutSolver.getStatus() << endl;
      report3 (cutSolver, Cut);
   }
   catch (IloException& ex) {
      cerr << "Error: " << ex << endl;
   }
   catch (...) {
      cerr << "Error" << endl;
   }

   env.end();

   return 0;
}
Exemplo n.º 26
0
void AssetAllocationModel::BuildCplexModel(IloEnv &env, IloModel &model, IloExpr &objective, unsigned int stage, const double *prev_decisions, const double *scenario, vector<IloNumVar> &decision_vars, vector<IloRange> &dual_constraints) const {
	//assets count N
	unsigned int assets = GetAssetsCount();
	bool root_node = (stage == 1);
	bool last_stage = (stage == GetStagesCount());
	double conf_inv = 1 - param_.confidence;
	double conf_inv_other = 1 - param_.confidence_other;

	IloNumVarArray x(env, assets);
	for (unsigned int i = 0; i < assets; ++i) {
		//zero lower bound
		x[i] = IloNumVar(env, 0.0);

		//max profit = min negative loss
		if (!root_node) {
			switch (param_.risk_measure) {
			case RISK_CVAR_NESTED:
				objective += -1 * x[i];
				break;
			case RISK_CVAR_MULTIPERIOD:
				objective += -1 * param_.expectation_coefficients[stage - 1] * x[i];
				break;
			}
		}

		decision_vars.push_back(x[i]);
	}
	model.add(x);

	//var c = positive value in the cvar
	IloNumVar c(env, 0.0);
	if (!root_node && (param_.risk_measure == RISK_CVAR_MULTIPERIOD)) {
		//objective with risk aversion coef lambda
		objective += param_.risk_coefficients[stage - 1] / conf_inv * c;
		model.add(c);
	}

	//var c_other = positive value in the cvar
	IloNumVar c_other(env, 0.0);
	if (!root_node && (param_.risk_measure == RISK_CVAR_MULTIPERIOD)) {
		//objective with risk aversion coef lambda
		objective += param_.risk_coefficients_other[stage - 1] / conf_inv_other * c_other;
		model.add(c_other);
	}

	//var var = variable to calculate CVaR = VaR level
	IloNumVar var(env, GetRecourseLowerBound(stage), GetRecourseUpperBound(stage));
	//objective according to the risk aversion lambda
	if (!last_stage) {
		//last stage has no recourse
		objective += param_.risk_coefficients[stage] * var;
	}
	model.add(var);
	decision_vars.push_back(var);

	//var var_other = variable to calculate CVaR = VaR level
	IloNumVar var_other(env, GetRecourseLowerBound(stage), GetRecourseUpperBound(stage));
	//objective according to the risk aversion lambda
	if (!last_stage) {
		//last stage has no recourse
		objective += param_.risk_coefficients_other[stage] * var_other;
	}
	model.add(var_other);
	decision_vars.push_back(var_other);

	//transaction costs dummy variable
	IloNumVarArray trans(env, assets);
	for (unsigned int i = 0; i < assets; ++i) {
		//zero lower bound
		trans[i] = IloNumVar(env, 0.0);
	}
	if (!root_node) {
		model.add(trans);
	}

	//constraint capital = sum of the weights equals initial capital one
	IloExpr cap_expr(env);
	double transaction_coef = param_.transaction_costs;
	for (unsigned int i = 0; i < assets; ++i) {
		cap_expr += x[i];
		if (!root_node) {
			cap_expr += transaction_coef * trans[i];
		}
	}
	double total_capital;
	if (root_node) {
		//no parent, init the capital with 1
		total_capital = 1.0;
	}
	else {
		//sum up the capital under this scenario
		total_capital = CalculateCapital(prev_decisions, scenario);
	}
	IloRange capital(env, total_capital, cap_expr, total_capital);
	model.add(capital);
	dual_constraints.push_back(capital);

	//constraint transaction costs
	IloRangeArray costs_pos(env);
	IloRangeArray costs_neg(env);
	if (!root_node) {
		for (unsigned int i = 0; i < assets; ++i) {
			//current position in asset i
			double parent_value = scenario[i] * prev_decisions[i]; //decisions and scenarios have the same order here, decisions start with allocations

			//positive and negative part of linearization for absolute value
			IloExpr cost_expr_pos(env);
			IloExpr cost_expr_neg(env);
			cost_expr_pos += x[i];
			cost_expr_pos += -1 * trans[i];
			cost_expr_neg += -1 * x[i];
			cost_expr_neg += -1 * trans[i];
			costs_pos.add(IloRange(env, cost_expr_pos, parent_value));
			costs_neg.add(IloRange(env, cost_expr_neg, -parent_value));

			dual_constraints.push_back(costs_pos[i]);
			dual_constraints.push_back(costs_neg[i]);
		}
		model.add(costs_pos);
		model.add(costs_neg);
	}

	//contraint the positive part "c" of the CVaR value
	IloExpr cvar_expr(env);
	IloRange cvar;
	if (!root_node && (param_.risk_measure == RISK_CVAR_MULTIPERIOD)) {
		cvar_expr += c; //the varible itself
		for (unsigned int i = 0; i < assets; ++i) {
			cvar_expr += x[i]; //-c transp x
		}
		double parent_var = prev_decisions[assets]; //var is right after the allocations in decision vector
		cvar = IloRange(env, -parent_var, cvar_expr); //previous value at risk
		model.add(cvar);
		dual_constraints.push_back(cvar);
	}

	//contraint the positive part "c_other" of the CVaR value
	IloExpr cvar_expr_other(env);
	IloRange cvar_other;
	if (!root_node && (param_.risk_measure == RISK_CVAR_MULTIPERIOD)) {
		cvar_expr_other += c_other; //the varible itself
		for (unsigned int i = 0; i < assets; ++i) {
			cvar_expr_other += x[i]; //-c transp x
		}
		double parent_var_other = prev_decisions[assets + 1]; //var_other is right after var in the decisions vector
		cvar_other = IloRange(env, -parent_var_other, cvar_expr_other); //previous value at risk
		model.add(cvar_other);
		dual_constraints.push_back(cvar_other);
	}

}
Exemplo n.º 27
0
static void populatebyrow (IloModel model, IloNumVarArray x, IloRangeArray c) {
  
  IloEnv env = model.getEnv();
  IloNumArray costs(env);
  IloNumArray time(env);
IloNumArray product(env);

  int costs_array[]  = {1,1,1,10,1,12,2,2,5,10};
  int time_array[]  = {10,1,7,3,2,3,2,3,7,1};
  int product_array[]  = {0,3,1,2,-2,0,0,0,0,0};
  

  for(int i=0;i<10;i++)
    costs.add(costs_array[i]);

  for(int i=0;i<10;i++)
    time.add(time_array[i]);

  for(int i=0;i<10;i++)
    product.add(product_array[i]);



  x.add(IloBoolVar(env,"x12")); //0
  x.add(IloBoolVar(env,"x24")); //1
  x.add(IloBoolVar(env,"x46")); //2
  x.add(IloBoolVar(env,"x13")); //3
  x.add(IloBoolVar(env,"x32")); //4
  x.add(IloBoolVar(env,"x35")); //5
  x.add(IloBoolVar(env,"x56")); //6
  x.add(IloBoolVar(env,"x25")); //7
  x.add(IloBoolVar(env,"x34")); //8
  x.add(IloBoolVar(env,"x45")); //9


x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s2")); //10
x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s3")); //11
x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s4")); //12
x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s5")); //13
x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s1")); //14
x.add(IloNumVar(env,0,IloInfinity,ILOINT,"s6")); //15

x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q2")); //16
x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q3")); //17
x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q4")); //18
x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q5")); //19
x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q1")); //20
x.add(IloNumVar(env,0,IloInfinity,ILOINT,"q6")); //21



  
  model.add(IloMinimize(env, costs[0]*x[0] + costs[1]*x[1] + costs[2]*x[2] + costs[3]*x[3] + costs[4]*x[4] + costs[5]*x[5] + costs[6]*x[6] + costs[7]*x[7] + costs[8]*x[8] + costs[9]*x[9]));
  c.add(x[0]+ x[3] == 1); // arcs sortant du noeud de depart
  c.add(x[2]+ x[6] == 1); // arcs entrant au noeud d arrivee
  c.add(x[1]+ x[7] - x[0] - x[4] == 0);
  c.add(x[8]+ x[5] + x[4] - x[3] == 0);
  c.add(x[9]+ x[2] - x[1] - x[8] == 0);
  c.add(x[6]- x[7] - x[5] - x[9] == 0);
  c.add(time[0]*x[0] + time[1]*x[1] + time[2]*x[2] + time[3]*x[3] + time[4]*x[4] + time[5]*x[5] + time[6]*x[6] + time[7]*x[7] + time[8]*x[8] + time[9]*x[9] <= 14);
//c.add(product[0]*x[0] + product[1]*x[1] + product[2]*x[2] + product[3]*x[3] + product[4]*x[4] + product[5]*x[5] + product[6]*x[6] + product[7]*x[7] + product[8]*x[8] + product[9]*x[9] <= 4);

c.add(x[14]+time[0]-1000*(1-x[0]) - x[10]<= 0);
c.add(x[20]+product[0]-1000*(1-x[0]) - x[16]<= 0);


c.add(x[10]+time[1]-1000*(1-x[1]) - x[12]<= 0);
c.add(x[16]+product[1]-1000*(1-x[1]) - x[18]<= 0);
c.add(x[18]-product[1]-1000*(1-x[1]) - x[16]<= 0);


c.add(x[12]+time[2]-1000*(1-x[2]) - x[15]<= 0);
c.add(x[18]+product[2]-1000*(1-x[2]) - x[21]<= 0);
c.add(x[21]-product[2]-1000*(1-x[2]) - x[18]<= 0);


c.add(x[14]+time[3]-1000*(1-x[3]) - x[11]<= 0);
c.add(x[20]+product[3]-1000*(1-x[3]) - x[17]<= 0);
c.add(x[17]-product[3]-1000*(1-x[3]) - x[20]<= 0);

c.add(x[13]+time[6]-1000*(1-x[6]) - x[15]<= 0);
c.add(x[19]+product[6]-1000*(1-x[6]) - x[21]<= 0);

c.add(x[10]+time[7]-1000*(1-x[7]) - x[13]<= 0);
c.add(x[16]+product[7]-1000*(1-x[7]) - x[19]<= 0);

c.add(x[12]+time[9]-1000*(1-x[9]) - x[13]<= 0);
c.add(x[18]+product[9]-1000*(1-x[9]) - x[19]<= 0);

c.add(x[11]+time[4]-1000*(1-x[4]) - x[10] <=0);
c.add(x[17]+product[4]-1000*(1-x[4]) - x[16]<= 0);
c.add(x[16]-product[4]-1000*(1-x[4]) - x[17]<= 0);


c.add(x[11]+time[8]-1000*(1-x[8]) - x[12]<= 0);
c.add(x[17]+product[8]-1000*(1-x[8]) - x[18]<= 0);

c.add(x[11]+time[5]-1000*(1-x[5]) - x[13]<= 0);
c.add(x[17]+product[5]-1000*(1-x[5]) - x[19]<= 0);



c.add(5 <= x[10] <= 7);
c.add(2 <= x[11] <= 5);
c.add(5 <= x[12] <= 9);
c.add(0 <= x[13] <= 20);
c.add(0 <= x[14] <= 0);
c.add(0 <= x[15] <= 14);

/*
c.add(2 <= x[17] <= 4);
c.add(0 <= x[16] <= 2);
c.add(3 <= x[18] <= 4);

c.add(0 <= x[19] <= 1000);
//c.add(0 <= x[20] <= 0);*/
c.add(3 <= x[21] <= 4);

c.add( x[20] == 1);









  model.add(c);
}
Exemplo n.º 28
0
ILOSTLBEGIN

vector<double> solve_qp_cplex(QP* qp, bool& success)
{
	vector<double> res(qp->num_var, 0);

	IloEnv env;

	try {

		IloModel model(env);

		// variables 
		IloNumVarArray var(env);

		for (int i=0; i<qp->num_var; i++)
		{
			if (qp->binary_idx[i]==0)
				var.add(IloNumVar(env, qp->lb[i], qp->ub[i]));
			else
				var.add(IloNumVar(env, qp->lb[i], qp->ub[i], ILOINT));
		}

		// constraints
		IloRangeArray con(env);
		//TODO remove these fake constraints
		for (int i=0; i<qp->num_var; i++)
		{
			con.add( var[i]<= 1e10);
		}

		// iterate over constraint matrix
		for (int i=0; i<qp->b.size(); i++)
		{
			vector<int>* idx = NULL;
			vector<float>* coef = NULL;
			int ret = qp->A.get(&idx, &coef, i);
			assert(idx!=NULL);
			assert(coef!=NULL);
			assert(ret>0);
			assert(idx->size()==coef->size());

			IloNumExpr c_expr(env);
			for (int j=0; j<idx->size(); j++)
			{
				//printf("j:%i %.3f %i (num_var: %i)\n", j, coef->at(j), idx->at(j), qp->num_var);
				assert(idx->at(j)<qp->num_var);
				c_expr+= coef->at(j)*var[idx->at(j)];
			}
			if (qp->eq_idx[i]>0)
			{
				con.add(c_expr == qp->b[i]);
				//env.out() << i << c_expr << "==" << qp->b[i] << endl;
			}
			else
			{
				con.add(c_expr <= qp->b[i]);
				//env.out() << i << c_expr << "<=" << qp->b[i] << endl;
			}
		}

		// objective
		IloNumExpr obj_expr(env);
		qp->Q.reset_it();
		while (true)
		{
			int i=0;
			int j=0;
			float val = qp->Q.next(&i, &j);
			//printf("%i %i %.2f\n", i, j, val);
			if (i==-1)
				break;
			assert(i<qp->num_var && j<qp->num_var);
			obj_expr+= var[i] * var[j] * val;
		}

		for (int i=0; i<qp->F.size(); i++)
		{
			if (qp->F[i]!=0)
				obj_expr+= var[i] * qp->F[i];
		}

		IloObjective obj(env, IloMinimize(env, obj_expr));
		//model.add(IloMinimize(env, var[0] + 2 * var[1] + 3 * var[2] + var[3]));

		//env.out() << "objective:  " << IloMinimize(env, obj_expr) << endl;
		//env.out() << "constraints:  " << con << endl;
		// create model
		//model.add(var);
		model.add(con);
		model.add(obj);

		// solve...
		IloCplex cplex(model);
		cplex.solve();

		IloNumArray vals(env);
		cplex.getValues(vals, var);
		//env.out() << "Values        = " << vals << endl;
		//cplex.getSlacks(vals, con);
		//env.out() << "Slacks        = " << vals << endl;

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


		for (int i=0; i<qp->num_var; i++)
			res[i] = vals[i];
	}
	catch (IloException& e) 
	{
		cerr << "Concert exception caught: " << e << endl;
		success = false;
	}
	catch (...)
	{
		cerr << "Unknown exception caught" << endl;
		success = false;
	}
	env.end();
	return res;
}
Exemplo n.º 29
0
int CProblem::setModel() {
	//time_t start, end;

	numvar = 1+n; // lambda + all c;

	IloEnv  env;
	try {
		IloModel model(env);
		IloCplex cplex(env);

		/*Variables*/
		IloNumVar lambda(env, "lambda");
		IloNumVarArray c(env, n);//
		for (unsigned int u=0; u<n; u++) {
			std::stringstream ss;
			ss << u;
			std::string str = "c" + ss.str();
			c[u]=IloNumVar(env, str.c_str());
		}

		IloArray<IloIntVarArray> z(env,n);
		for (unsigned int u=0; u<n; u++) {
			z[u]= IloIntVarArray(env, n);
			for (unsigned int v=0; v<n; v++) {
				std::stringstream ss;
				ss << u;
				ss << v;
				std::string str = "z" + ss.str();
				z[u][v] = IloIntVar(env, 0, 1, str.c_str());
			}
		}

		/* Constant M*/
		
		int M=n*max_d;
		UB = M;

		/*  Objective*/
		model.add(IloMinimize(env, lambda));
		//model.add(IloMinimize(env, IloSum(c)));
		/*Constrains*/
		model.add(lambda - UB <= 0);

		/* d=function of the distance */
		IloArray<IloNumArray> Par_d(env,n);
		for (unsigned int u=0; u<n; u++) {
			Par_d[u]=IloNumArray(env,n);
			for (unsigned int v=0; v<n; v++) {
				Par_d[u][v]=d[u][v];
			}
		}

		for (unsigned u=0; u<n; u++) {
			for (unsigned v=0; v<u; v++) {
				model.add(c[v]-c[u]+M*   z[u][v]  >= Par_d[u][v] );
				model.add(c[u]-c[v]+M*(1-z[u][v]) >= Par_d[u][v]);
				numvar++; // + z[u][v]
			}
		}

/*
			for (unsigned i=0; i<sqrt(n)-1; i=i+1) {
				for (unsigned j=0; j<sqrt(n)-1; j=j+1) {
				    //square lattice
				    model.add (c[i*sqrt(n)+j]     +c[i*sqrt(n)+j+1] +
					       c[(i+1)*sqrt(n)+j] +c[(i+1)*sqrt(n)+j+1]>= 16-4*sqrt(2));  // Bedingung fuer Quadratischen Gridgraph und d(x) = 3-x
//					
					// triangular lattice
//					model.add (c[i*5+j]+c[i*5+j+1] +
//					           c[(i+1)+j] >= 4);  // Bedingung fuer Quadratischen Gridgraph und d(x) = 3-x
//					model.add (c[i*sqrt(n)+j]+c[i*sqrt(n)+j+1] +
//					           c[(i+1)*sqrt(n)+j]+c[(i+1)*sqrt(n)+j+1] >= 22 - 4*sqrt(2));  // Bedingung fuer Quadratischen Gridgraph und d(x) = 4-x

				}
			}
*/

/*
			for (unsigned i=0; i<sqrt(n)-2; i+=3) {
				for (unsigned j=0; j<sqrt(n)-2; j+=3) {
//					model.add (c[i*sqrt(n)+j]    + c[i*sqrt(n)+j+1]    + c[i*sqrt(n)+j+2] +
//					           c[(i+1)*sqrt(n)+j]+ c[(i+1)*sqrt(n)+j+1]+ c[(i+1)*sqrt(n)+j+2] +
//					           c[(i+2)*sqrt(n)+j]+ c[(i+2)*sqrt(n)+j+1]+ c[(i+2)*sqrt(n)+j+2]
//					           >= 60-17*sqrt(2)-3*sqrt(5));  // Bedingung fuer Quadratischen Gridgraph und d(x) = 3-x
//					model.add (c[i*sqrt(n)+j]    + c[i*sqrt(n)+j+1]    + c[i*sqrt(n)+j+2] +
//					           c[(i+1)*sqrt(n)+j]+ c[(i+1)*sqrt(n)+j+1]+ c[(i+1)*sqrt(n)+j+2] +
//					           c[(i+2)*sqrt(n)+j]+ c[(i+2)*sqrt(n)+j+1]+ c[(i+2)*sqrt(n)+j+2]
//					           >= 82-8*sqrt(2)-2*sqrt(5));  // Bedingung fuer Quadratischen Gridgraph und d(x) = 4-x
				}
			}

*/
		for (unsigned int v=0; v<n; v++) {
			IloExpr expr;
			model.add (c[v] <= lambda);
			model.add (c[v] >= 0);
			expr.end();
		}



		std::cout << "Number of variables " << numvar << "\n";

		/* solve the Model*/
		cplex.extract(model);
		cplex.exportModel("L-Labeling.lp");

		/*
		start = clock();
		int solveError = cplex.solve();
		end = clock ();
		*/

		IloTimer timer(env);
		timer.start();
		int solveError = cplex.solve();
		timer.stop();

		if ( !solveError ) {
			std::cout << "STATUS : "<< cplex.getStatus() << "\n";
			env.error() << "Failed to optimize LP \n";
			exit(1);
		}
		//Info.time = (double)(end-start)/(double)CLOCKS_PER_SEC;
		Info.time = timer.getTime();

		std::cout << "STATUS : "<< cplex.getStatus() << "\n";
		/* get the solution*/
		env.out() << "Solution status = " << cplex.getStatus() << "\n";
		numconst = cplex.getNrows();
		env.out() << " Number of constraints = " << numconst << "\n";
		lambda_G_d=cplex.getObjValue();
		env.out() << "Solution value  = " << lambda_G_d << "\n";
		for (unsigned int u=0; u<n; u++) {
			C.push_back(cplex.getValue(c[u]));
			std::cout << "c(" << u << ")=" << C[u]<< " ";
		}
		std::cout <<"\n";
		/*
		for (unsigned int u=0; u<n; u++) {
			for (unsigned int v=0; v<u; v++) {
				std::cout<< "z[" << u <<"][" << v << "]="<< cplex.getValue( z[u][v]) << " ";
				Z.push_back(cplex.getValue( z[u][v]));
			}
			std::cout << "\n";
		}
		std::cout <<"\n";
		 */
	}	// end try
	catch (IloException& e) {
		std::cerr << "Concert exception caught: " << e << std::endl;
	}
	catch (...) {
		std::cerr << "Unknown exception caught" << std::endl;
	}
	env.end();
	return 0;
}
Exemplo n.º 30
0
/** Create the dual of a linear program.
 * The function can only dualize programs of the form
 * <code>Ax <= b, x >= 0</code>. The data in <code>primalVars</code> and
 * <code>dualRows</code> as well as in <code>primalRows</code> and
 * <code>dualVars</code> is in 1-to-1-correspondence.
 * @param primalObj  Objective function of primal problem.
 * @param primalVars Variables in primal problem.
 * @param primalRows Rows in primal problem.
 * @param dualObj    Objective function of dual will be stored here.
 * @param dualVars   All dual variables will be stored here.
 * @param dualRows   All dual rows will be stored here.
 */
void BendersOpt::makeDual(IloObjective const &primalObj,
                          IloNumVarArray const &primalVars,
                          IloRangeArray const &primalRows,
                          IloObjective *dualObj,
                          IloNumVarArray *dualVars,
                          IloRangeArray *dualRows)
{
   // To keep the code simple we only support problems
   // of the form Ax <= b, b >= 0 here. We leave it as a reader's
   // exercise to extend the function to something that can handle
   // any kind of linear model.
   for (IloInt j = 0; j < primalVars.getSize(); ++j)
      if ( primalVars[j].getLB() != 0 ||
           primalVars[j].getUB() < IloInfinity )
      {
         std::stringstream s;
         s << "Cannot dualize variable " << primalVars[j];
         throw s.str();
      }
   for (IloInt i = 0; i < primalRows.getSize(); ++i)
      if ( primalRows[i].getLB() > -IloInfinity ||
           primalRows[i].getUB() >= IloInfinity )
      {
         std::stringstream s;
         s << "Cannot dualize constraint " << primalRows[i];
         std::cerr << s.str() << std::endl;
         throw s.str();
      }

   // The dual of
   //   min/max c^T x
   //       Ax <= b
   //        x >= 0
   // is
   //   max/min y^T b
   //       y^T A <= c
   //           y <= 0
   // We scale y by -1 to get >= 0

   IloEnv env = primalVars.getEnv();
   IloObjective obj(env, 0.0,
                    primalObj.getSense() == IloObjective::Minimize ?
                    IloObjective::Maximize : IloObjective::Minimize);
   IloRangeArray rows(env);
   IloNumVarArray y(env);
   std::map<IloNumVar,IloInt,ExtractableLess<IloNumVar> > v2i;
   for (IloInt j = 0; j < primalVars.getSize(); ++j) {
      IloNumVar x = primalVars[j];
      v2i.insert(std::map<IloNumVar,IloInt,ExtractableLess<IloNumVar> >::value_type(x, j));
      rows.add(IloRange(env, -IloInfinity, 0, x.getName()));
   }
   for (IloExpr::LinearIterator it = primalObj.getLinearIterator(); it.ok(); ++it)
      rows[v2i[it.getVar()]].setUB(it.getCoef());

   for (IloInt i = 0; i < primalRows.getSize(); ++i) {
      IloRange r = primalRows[i];
      IloNumColumn col(env);
      col += obj(-r.getUB());
      for (IloExpr::LinearIterator it = r.getLinearIterator(); it.ok(); ++it)
         col += rows[v2i[it.getVar()]](-it.getCoef());
      y.add(IloNumVar(col, 0, IloInfinity, IloNumVar::Float, r.getName()));
   }

   *dualObj = obj;
   *dualVars = y;
   *dualRows = rows;
}