コード例 #1
0
ファイル: instance.cpp プロジェクト: shidanxu/solver
 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();    
 }
コード例 #2
0
ファイル: ilosocpex1.cpp プロジェクト: renvieir/ioc
int
main (void)
{
   IloEnv env;
   int retval = -1;

   try {
      // Create the model.
      IloModel model(env);
      IloCplex cplex(env);
      IloObjective obj(env);
      IloNumVarArray vars(env);
      IloRangeArray rngs(env);
      IloIntArray cone(env);
      createmodel(model, obj, vars, rngs, cone);

      // Extract model.
      cplex.extract(model);

      // Solve the problem. If we cannot find an _optimal_ solution then
      // there is no point in checking the KKT conditions and we throw an
      // exception.
      cplex.setParam(IloCplex::Param::Barrier::QCPConvergeTol, CONVTOL);
      if ( !cplex.solve() || cplex.getStatus() != IloAlgorithm::Optimal )
         throw string("Failed to solve problem to optimality");

      // Test the KKT conditions on the solution.
      if ( !checkkkt (cplex, obj, vars, rngs, cone, TESTTOL) ) {
         env.error() << "Testing of KKT conditions failed." << endl;
      }
      else {
         env.out() << "Solution status: " << cplex.getStatus() << endl;
         env.out() << "KKT conditions are satisfied." << endl;
         retval = 0;
      }

      env.end();
   } catch (IloException &e) {
      cerr << "IloException: " << e << endl;
      if (env.getImpl())
         env.end();
      ::abort();
   } catch (string& e) {
      cerr << e << endl;
      if (env.getImpl())
         env.end();
      ::abort();
   }
   return retval;
}
コード例 #3
0
ファイル: iloqpex1.cpp プロジェクト: andreasmattas/testcode
int
main (int argc, char **argv)
{
   IloEnv   env;
   try {
      IloModel model(env);
      IloNumVarArray var(env);
      IloRangeArray con(env);

      populatebyrow (model, var, con);

      IloCplex cplex(model);

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

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

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

   env.end();

   return 0;
}  // END main
コード例 #4
0
static void
solveanddisplay   (IloEnv env, IloCplex cplex, IloNumVarArray var,
                   IloRangeArray con)
{
      // Optimize the problem and obtain solution.
      if ( !cplex.solve() ) {
         env.error() << "Failed to optimize LP" << endl;
         throw(-1);
      }

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

}  // END solveanddisplay
コード例 #5
0
ファイル: CAP.cpp プロジェクト: tikhoncheva/work
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;
}
コード例 #6
0
IloNum columnGeneration (IloCplex2 subSolver, IloCplex rmpSolver, 
	IloNumVarArray3 x, IloNumVarArray2 z, IloNumVarArray2 lambda,
	IloObjective2 reducedCost, IloObjective rmpObj,
	IloRangeArray2 maintConEng, IloRangeArray2 removeMod, IloRangeArray2 convex,
	IloNumArray2 addXCol, IloNumArray addZCol,
	IloNumArray2 priceRemoveMod, IloNumArray2 priceMaintConEng, IloNumArray priceConvex, 
	const IloNumArray2 compCosts, const IloNumArray convexityCoef,
	IloBool weightedDW_in, IloBool allowCustomTermination,
	IloInt relChangeSpan, IloNum relChange) {

	// extract optimization enviroment
	IloEnv env = rmpSolver.getEnv();
	
	
	// ANALYSIS: write to file
	const char*	output = "results/colGen_analysis.dat";
	
	// variable declarations..	
	
	// loop counters
	IloInt i, m, t, testCounter;

	testCounter = 0;

	// declare two clock_t objects for start and end time.		
	clock_t start, end;

	// declare an array of size NR_OF_MODULES to temporarily hold the
	// reduced costs from the NR_OF_MODULES different subproblems.
	IloNumArray redCosts(env, NR_OF_MODULES);

	IloBool weightedDW = weightedDW_in;

	// declare an array to hold the RMP objective values: e.g. add
	// one value to array for each iteration.
//	IloNumArray objValues(env);

	// declare an array to hold the lower bounds for the full MP, given
	//  	z(RMP)* + sum_[m in subproblems] redCost(m)^* <= z(full MP)^* <= z(RMP)^*
//	IloNumArray lowerBounds(env);

	// declare two temp IloNum objects for temporarily hold rmp objective value
	// and full MP lower bound. (full: MP with _all_ columns availible).
	IloNum tempRmpObj, tempLowerBound, bestLowerBound;
	bestLowerBound = -IloInfinity;

	// also use a num-array to hold the REL_CHANGE_SPAN most
	// recent RMP objective values. Used to the relative change
	// break criteria (if improvement by col-gen becomes to
	// "slow"/"flat").
	IloNumArray recentObjValues(env, REL_CHANGE_SPAN);

	// declare and initiate col-gen iteration counter
	IloInt itNum = 0;

	// ---- weighted DW decomp - for less trailing in colgen.
	//IloBool weightedDW = IloTrue;

	// declare two IloNum-array to hold all 2x (NR_OF_MODULES x TIME_SPAN)
	// dual vars - or specific, best dual vars (giving highest lower bound)
	IloNumArray2 dualsModBest(env);
	IloNumArray2 dualsEngBest(env);

	// temp..
	//IloBoolArray continueSub(env, NR_OF_MODULES);
	
	// allocate memory for sub-arrays
	for (m = 0; m < NR_OF_MODULES; m++) {

		dualsModBest.add(IloNumArray(env,TIME_SPAN));	
		dualsEngBest.add(IloNumArray(env,TIME_SPAN));

		//continueSub[m] = IloTrue;

		// and maybe: initially set all dual vars to 0?
		for (t = 0; t < TIME_SPAN; t++) {
			dualsModBest[m][t] = 0.0;
			dualsEngBest[m][t] = 0.0;
		}
	}

	// also, a weight for weighted DW:
	IloNum weight = 2.0;

	// counter number of improvements of "best duals"
	IloInt nrOfImprov = 0;

	// const used in weigt
	IloNum weightConst = DW_WEIGHT;

	// initiate numarray for recent objective values
	// UPDATE: this is not really needed now as we check the
	// relative change break criteria only when we know this
	// vector has been filled by REL_CHANGE_SPAN "proper" values...
	recentObjValues[0] = 0.0;
	for (i = 1; i < REL_CHANGE_SPAN; i++) {
		recentObjValues[i] = 0.0;
	}						

	// model before generation start:
	//rmpSolver.exportModel("rmpModel.lp");

	//write results to file
/*	ofstream outFile(output);

	outFile << "Writing out results from initial column generation, T=" << TIME_SPAN << endl
		<< "Form: [(itNum) (dual solution value) (upper bound = tempRmpObj)]" << endl << endl;*/


	//cout << endl << "WE GOT OURSELVES A SEGMENTATION FAULT!" << endl;

	// start timer
	start = clock();

	// also use an alternative time counter..
	time_t start2, end2;
	start2 = time(NULL);

	// loop until break...
	for (;;) {

		// increase iteration counter
		itNum++;

		// solve master
		if ( !rmpSolver.solve() ) {
       			env.error() << "Failed to optimize RMP." << endl;
			throw(-1);
		}
		
		// get the rmp objective value
		tempRmpObj = rmpSolver.getValue(rmpObj);

		// add to objective value array (size: iterations)
	//	objValues.add(tempRmpObj);

		// update recentObjValues:
		recentObjValues.remove(0);
			// remove oldest:
		recentObjValues.add(tempRmpObj);
			// save newest		

		// report something (... report1() )
		// UPDATE: colgen is to quick for anything to see anything reported... so skip this

		// update weight: weight = min{ 2,
		if (itNum>1) { 
			weight = (IloNum(itNum - 1) + IloNum(nrOfImprov))/2;
		}
		if ( weight > weightConst) {
			weight = weightConst;
		}	


		// update duals
		// -> updates obj. functions for subproblems (w.r.t. duals)
		for (m = 0; m < NR_OF_MODULES; m++) {

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

			for (t = 0; t < TIME_SPAN; t++) {

				// if we try weightedWD decomp:
				// for first iteration: just extract duals which will become best duals
				if (itNum > 1 && weightedDW) {

					// price associated with const. removeMod
					priceRemoveMod[m][t] = (rmpSolver.getDual(removeMod[m][t]))/weight + (weight-1)*(dualsModBest[m][t])/weight;

					// price associated with const. maintConEng
					priceMaintConEng[m][t] = (rmpSolver.getDual(maintConEng[m][t]))/weight + (weight-1)*(dualsEngBest[m][t])/weight;	

				}
				// normally:
				else {

					// price associated with const. removeMod
					priceRemoveMod[m][t] = rmpSolver.getDual(removeMod[m][t]);

					// price associated with const. maintConEng
					priceMaintConEng[m][t] = rmpSolver.getDual(maintConEng[m][t]);
				}

				//cout << "priceRemoveMod[m][t] = " << priceRemoveMod[m][t] << endl;

				// update subproblem obj. function coefficients for z[m][t] vars:
				reducedCost[m].setLinearCoef(z[m][t],-(priceRemoveMod[m][t] + priceMaintConEng[m][t]));
			} 

			//cin.get();

			// rmpSolver.getDuals(priceRemoveMod[m], removeMod[m]);
			// rmpSolver.getDuals(priceMaintConEng[m], maintConEng[m]);
			// priceConvex[m] = -rmpSolver.getDual(convex[m][0]);
				
			// if we try weightedWD decomp:
			// for first iteration: just extract duals which will become best duals
	/*		if (itNum > 1 && weightedDW) {

				// price associated with convexity constraint
				priceConvex[m] = -abs(rmpSolver.getDual(convex[m][0]))/weight - (weight-1)*(dualsConvBest[m])/weight;
			} */
		
			// price associated with convexity constraint
			priceConvex[m] = -abs(rmpSolver.getDual(convex[m][0]));

			// update subproblem obj. function's constant term
			reducedCost[m].setConstant(priceConvex[m]);
			
		} // END of updating duals

		// solve subproblems
		for (m = 0; m < NR_OF_MODULES; m++) {

			//if (continueSub[m]) {

				// solve subproblem m
				cout << endl << "Solving subproblem #" << (m+1) << "." << endl;
				if ( !subSolver[m].solve() ) {
       					env.error() << "Failed to optimize subproblem #" << (m+1) << "." << endl;
       					throw(-1);
				}
		
				// extract reduced cost: subSolver[m].getValue(reducedCost[m])
				// into a IloNumArray(env, NR_OF_MODULES) at position m.				
				redCosts[m] = subSolver[m].getValue(reducedCost[m]);

				//env.out() << endl << "Reduced cost for problem #" << (m+1) << ":" << redCosts[m] << endl;

				// if reduced cost is negative, att optimal solution to
				// column pool Q(m)
				if (!(redCosts[m] > -RC_EPS)) {
					
					// add column		
					addColumn(subSolver[m], x[m], z[m], lambda[m], rmpObj, maintConEng[m], removeMod[m],
						convex[m], addXCol, addZCol, compCosts[m], convexityCoef);

					//env.out() << endl << "Added a column to pool Q(" << (m+1) 
					//	<< "). Lambda[" << (m+1) << "].size = " << lambda[m].getSize() << endl; 

					testCounter++;
				}	
				//else {
				//	continueSub[m] = IloFalse;
				//}
			//}
			//else {
			//	redCosts[m] = 0;
			//}	


		} // END of solving subproblems (for this iteration)

		// calculate lower bound on full MP
		tempLowerBound = tempRmpObj + sumArray(redCosts);

		// update best lower bound
		if (tempLowerBound > bestLowerBound) {
			bestLowerBound = tempLowerBound;
		
			// increase counter for number of improved "best duals".
			nrOfImprov++;

			//cout << endl << "WHATEVAAAH" << endl;
			//cin.get();

			// save best duals
			for (m = 0; m < NR_OF_MODULES; m++) {
				for (t = 0; t < TIME_SPAN; t++) {			
					dualsModBest[m][t] = priceRemoveMod[m][t];
					dualsEngBest[m][t] = priceMaintConEng[m][t];
				}
			}
		}						

		// update lower bounds vector
		//lowerBounds.add(bestLowerBound);
		
		// ANALYSIS: print out to file:
		// [(itNum) (dual solution value) (upper bound = tempRmpObj)]
		//outFile << itNum << " " << tempLowerBound << " " << tempRmpObj << endl;

		// if the smallest reduced cost in the updated red-cost vector 
		// with NR_OF_MODULES entries is greater than -RC_EPS: break
		// otherwise, repeat.
		if (minMemberValue(redCosts) > -RC_EPS) {
			env.out() << endl << "All reduced costs non-negative: breaking." << endl;
			bestLowerBound = tempRmpObj;
			break;
		}

		// if relative change in objective value over the last REL_CHANGE_SPAN iterations is
		// less than REL_CHANGE, break.
		//if (allowCustomTermination && (itNum >= REL_CHANGE_SPAN) && (relativeImprovement(recentObjValues) < REL_CHANGE)) {
		if (allowCustomTermination && (itNum >= relChangeSpan) && (relativeImprovement(recentObjValues) < relChange)) {
			env.out() << endl << "Relative change smaller than pre-set acceptance: breaking." << endl;
			break;
		}													

		// if the gap currentUpperBound - currentLowerBound is small enough, break
		if ((tempRmpObj - bestLowerBound) < RC_EPS) {
			env.out() << endl << "Lower<>Upper bound gap less than pre-set acceptance: breaking." << endl;
			cout << endl << "(tempRmpObj - bestLowerBound) = " << (tempRmpObj - bestLowerBound) << endl;
			bestLowerBound = tempRmpObj;
			break;
		}


	} // END of column generation.
		
	// alternative: print the REL_CHANGE_SPAN most recent RMP objective values		
	env.out() << endl;
	/*for (i = 0; i < recentObjValues.getSize(); i++) {
		env.out() << "Recent #" << (i+1) << ": " << recentObjValues[i] << endl;
	}*/

	// solve master using final column setup
      	if ( !rmpSolver.solve() ) {
        	env.error() << "Failed to optimize RMP." << endl;
        	throw(-1);
      	}

	// also add final objective value to objective value array (size: iterations)
//	objValues.add(rmpSolver.getValue(rmpObj));

	// create IloNum object and extract the final RMP objective value.
	IloNum finalObj;
	finalObj = rmpSolver.getValue(rmpObj);

	// end program time counter(s)
	end = clock();
	end2 = time(NULL);

	// print result to file
	//outFile << endl << endl << "Final objective value: " << finalObj << endl
	//	<< "Time required for execution: " << (double)(end-start)/CLOCKS_PER_SEC << " seconds." << endl;

	// outfile.close()	
	//outFile.close(); 
	itNum = 0;
		// re- use iteration counter to count total number of columns generated

	// nr of columns generated from each subproblem		
	for (m = 0; m < NR_OF_MODULES; m++) {
		// ### outFile << "Number of columns generated from subproblem (m = " << m << "): " << (lambda[m].getSize() - 1) << endl;
		cout << "Number of columns generated from subproblem (m = " << m << "): " << (lambda[m].getSize() - 1) << endl;
		//outFile << "Pool (m = " << m << "): " << (lambda[m].getSize() - 1) << endl;
		
		itNum += lambda[m].getSize();
	}
 
	// ###
/*	outFile << endl << "Total number of columns generated: " << itNum << endl;
	outFile << "Time required for column generation: " << (double)(end-start)/CLOCKS_PER_SEC << " seconds." << endl;
	outFile << "ALTERNATIVE: Time required for colgen: " << end2-start2 << " seconds." << endl;
	outFile << "RMP objective function cost: " << finalObj << endl << endl;
	//outFile << "Objective function values for each iteration: " << endl;		
	//outFile << objValues;
	//outFile << endl << endl << "Lower bounds for each iteration: " << endl; 
	//outFile << lowerBounds;
	outFile.close(); */

	//cout << "Initial column generation complete, press enter to continue..." << endl;
	//cin.get();


	// print some results..
	/*env.out() << endl << "RMP objective function cost: " << finalObj << endl;
	env.out() << endl << "Size of objective value vector: " << objValues.getSize() << endl;
	env.out() << endl << "Nr of iterations: " << itNum << endl;	

	cout << endl << "Number of new columns generated: " << testCounter << endl;*/		

	// Note: to explicit output (void function), ass columns are added implicitely via 
	// income argument pointers.		
					
	// clear memory assigned to temporary IloNumArrays:
	redCosts.end();
	//objValues.end();	
	//lowerBounds.end();	
	recentObjValues.end();

	// save best duals
	for (m = 0; m < NR_OF_MODULES; m++) {
		dualsModBest[m].end();
		dualsEngBest[m].end();
	}
	dualsModBest.end();
	dualsEngBest.end();
	//continueSub.end();	

	//cout << endl << "NR OF IMPROVEMENTS: " << nrOfImprov << endl;
	//cin.get();

	// return lower bound
	return bestLowerBound;	

} // END of columnGeneration()
コード例 #7
0
ファイル: copy of CAP.cpp プロジェクト: tikhoncheva/work
int CProblem::setModel()
{
	//time_t start, end;

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

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

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

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

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

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

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


		
		// d(x) = 3 - x
		if (max_distance == 2) 
		{
		  // Sechsecke mit der Seitenlaenge 1
		  model.add(c[0]+c[2] +c[3] +c[5] +c[6] +c[9]>=16.6077);
		  model.add(c[1]+c[3] +c[4] +c[6] +c[7] +c[10]>=16.6077);
		  model.add(c[5]+c[8] +c[9] +c[12]+c[13]+c[16]>=16.6077);
		  model.add(c[6]+c[9] +c[10]+c[13]+c[14]+c[17]>=16.6077);
		  model.add(c[7]+c[10]+c[11]+c[14]+c[15]+c[18]>=16.6077);
		  model.add(c[13]+c[16]+c[17]+c[19]+c[20]+c[22]>=16.6077);
		  model.add(c[14]+c[17]+c[18]+c[20]+c[21]+c[23]>=16.6077);
		}
		
		//d(x) = 4 - x	
		if (max_distance == 3) 
		{
		  // Sechsecke mit der Seitenlaenge 1
		  model.add(c[0]+c[2] +c[3] +c[5] +c[6] +c[9]>=31.6077);
		  model.add(c[1]+c[3] +c[4] +c[6] +c[7] +c[10]>=31.6077);
		  model.add(c[5]+c[8] +c[9] +c[12]+c[13]+c[16]>=31.6077);
		  model.add(c[6]+c[9] +c[10]+c[13]+c[14]+c[17]>=31.6077);
		  model.add(c[7]+c[10]+c[11]+c[14]+c[15]+c[18]>=31.6077);
		  model.add(c[13]+c[16]+c[17]+c[19]+c[20]+c[22]>=31.6077);
		  model.add(c[14]+c[17]+c[18]+c[20]+c[21]+c[23]>=31.6077);
		}
		
		

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

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

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

		cplex.setParam(IloCplex::ClockType,1);
		IloTimer timer(env);
		timer.start();
		int solveError = cplex.solve();
		timer.stop();

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

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

	} // end try
	catch (IloException& e)
	{
		std::cerr << "Concert exception caught: " << e << std::endl;
	} catch (...)
	{
		std::cerr << "Unknown exception caught" << std::endl;
	}
	env.end();
	return 0;
}
コード例 #8
0
ファイル: iloqpex2.cpp プロジェクト: annaPolytech/PRD
int
main (int argc, char **argv)
{
   IloEnv env;
   try {
      IloModel model(env);
      IloCplex cplex(env);

      if (( argc != 3 )                             ||
          ( strchr ("opdbn", argv[2][0]) == NULL )  ) {
         usage (argv[0]);
         throw(-1);
      }

      switch (argv[2][0]) {
         case 'o':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::AutoAlg);
            break;
         case 'p':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Primal);
            break;
         case 'd':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Dual);
            break;
         case 'b':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Barrier);
            break;
         case 'n':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Network);
            break;
         default:
            break;
      }

      IloObjective   obj;
      IloNumVarArray var(env);
      IloRangeArray  rng(env);
      cplex.importModel(model, argv[1], obj, var, rng);

      cplex.extract(model);
      if ( !cplex.solve() ) {
         env.error() << "Failed to optimize LP" << endl;
         throw(-1);
      }

      IloNumArray vals(env);
      cplex.getValues(vals, var);
      env.out() << "Solution status = " << cplex.getStatus() << endl;
      env.out() << "Solution value  = " << cplex.getObjValue() << endl;
      env.out() << "Solution vector = " << vals << endl;
   }
   catch (IloException& e) {
      cerr << "Concert exception caught: " << e << endl;
   }
   catch (...) {
      cerr << "Unknown exception caught" << endl;
   }

   env.end();
   return 0;
}  // END main
コード例 #9
0
ファイル: CAP_HLTF2.cpp プロジェクト: tikhoncheva/work
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;
}
コード例 #10
0
ファイル: ilolpex7.cpp プロジェクト: annaPolytech/PRD
int
main (int argc, char **argv)
{
   IloEnv env;
   try {
      IloModel model(env);
      IloCplex cplex(env);

      if (( argc != 3 )                              ||
          ( strchr ("podhbnsc", argv[2][0]) == NULL )  ) {
         usage (argv[0]);
         throw(-1);
      }

      switch (argv[2][0]) {
         case 'o':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::AutoAlg);
            break;
         case 'p':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Primal);
            break;
         case 'd':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Dual);
            break;
         case 'b':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Barrier);
            cplex.setParam(IloCplex::Param::Barrier::Crossover, IloCplex::NoAlg);
            break;
         case 'h':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Barrier);
            break;
         case 'n':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Network);
            break;
         case 's':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Sifting);
            break;
         case 'c':
            cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Concurrent);
            break;
         default:
            break;
      }

      IloObjective   obj;
      IloNumVarArray var(env);
      IloRangeArray  rng(env);
      cplex.importModel(model, argv[1], obj, var, rng);

      cplex.extract(model);
      if ( !cplex.solve() ) {
         env.error() << "Failed to optimize LP" << endl;
         throw(-1);
      }

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

      for (IloInt i = 0; i < var.getSize(); i++) {
         if ( var[i].getName() ) env.out() << var[i].getName();
         else                    env.out() << "Fake" << i;
         env.out() << ": " << cplex.getValue(var[i]);
         try {  // basis may not exist
            env.out() << '\t' << cplex.getBasisStatus(var[i]);
         }
         catch (...) {
         }
         env.out() << endl;
      }

      env.out() << "Maximum bound violation = "
                << cplex.getQuality(IloCplex::MaxPrimalInfeas) << endl;
   }
   catch (IloException& e) {
      cerr << "Concert exception caught: " << e << endl;
   }
   catch (...) {
      cerr << "Unknown exception caught" << endl;
   }

   env.end();
   return 0;
}  // END main
コード例 #11
0
ファイル: calub.cpp プロジェクト: tramelon/branchbound
int calub(double &UB, double &LB, int Z[][T1+1], int U[][T1+1], int V[][T1+1], int W[][T1+1],float Znode[][T1+1], int budget, double costuvw)
	{
//	IloInt J=54;	//units
//	IloInt T=T1;	//time
//	IloInt N=Nn;    // buses
//	IloInt L=186;    // trans lines
IloEnv lazenv;
   NumMatrix laz_u(lazenv, J);
   NumMatrix laz_v(lazenv, J);
   NumMatrix laz_w(lazenv, J);
   for(IloInt j = 0; j < J; j++){
			laz_u[j] = IloNumArray(lazenv,T+1);
			laz_v[j] = IloNumArray(lazenv,T+1);
			laz_w[j] = IloNumArray(lazenv,T+1);
		}
   for(IloInt t = 0; t <= T; t++)
		for(IloInt j = 0; j < J; j++){
			laz_u[j][t] = U[j][t];  // pass start-up variables
			laz_v[j][t] = V[j][t];
			laz_w[j][t] = W[j][t];}

	IloInt m; // O(l),origin or line
	IloInt r; // D(l),destination of line
	IloNum scale=1; // nodal demand scale
	IloNum maxdelta= 1.57;
	double obj_val;
	IloNum ldpen=ldpena; // penalty for load shed
	IloInt uncdbug = budget;  // demand uncertain budget
	IloNum uncd = uncda; // uncertainty part / demand
//	double in_tlrn =  in_tlrn;//0.001 ; // in gap torrence,0.01
	double sol_gap = 0.005 ; // solver gap
	IloInt itrc_out = 0;
	IloInt res_itrc = 20;// initial set of scenarios in mas problem
	IloNum outgap = 1;
	IloNum outLB = -IloInfinity;
	IloNum outUB =  IloInfinity;
	double runningtime;
// NumMatrix dnt(env);
//		IloNum costuvw; //cost of start up and fixed cost
		IloNum Md; // penalty for dual
		IloNum sellprice = 0;
		IloInt it_out = 20; // # of out iterations
		ThreeDNumMatrix Zoutstar(env,it_out);
		 {for(IloInt it = 0; it < it_out; it++)
			   Zoutstar[it] = NumMatrix(env,N);
		  for(IloInt it = 0; it < it_out; it++)
				for(IloInt n = 0; n < N; n++)
					Zoutstar[it][n] = IloNumArray(env,T+1); }
		 for(IloInt it = 0; it < 2; it++)
			 for(IloInt n = 0; n < N; n++)
				 for(IloInt t = 0; t <= T; t++)
					 Zoutstar[it][n][t] = 0;
		ThreeDVarMatrix g(env,it_out);
		ThreeDVarMatrix goverline(env,it_out);
		ThreeDVarMatrix reserve(env,it_out);
		ThreeDVarMatrix plt(env,it_out);
		ThreeDVarMatrix dlnt(env,it_out);
		ThreeDVarMatrix delta(env,it_out);
		ThreeDBoolVarMatrix h(env,J); // start-up type
		IloNumVar beta(env, -IloInfinity,IloInfinity);
		NumMatrix Tsu(env, J);     // Tsu_gs
		NumMatrix Csu(env, J);     // Csu_gs
		NumMatrix Kjt(env, J);
		IloNumArray aj(env,J);    // no loads cost
		IloNumArray rj(env,J);    //
		IloNumArray cj(env,J);    // linear variable cost
		IloNumArray Gj(env,J);    // min output
		IloNumArray G0(env,J);    // Initial output
		IloNumArray Gjb(env,J);    // max output
		IloNumArray Dj(env,J); 	// number of hours j required to be off at the start period
		IloNumArray Uj(env,J); 	// number of hours j required to be up at the start period
		IloNumArray uj0(env,J);     //initial status of gen
		IloNumArray gj0(env,J);     //initial status of gen
		IloNumArray RU(env,J); 	// ramping up
		IloNumArray RD(env,J); 	// ramping down
		IloNumArray UT(env,J);     // min up
		IloNumArray UT0(env,J);    // online time before schedule
		IloNumArray UTr(env,J);    //
		IloNumArray DT(env,J);     // min down
		IloNumArray DT0(env,J);    // offline time before schedule
		IloNumArray DTr(env,J);    //
		IloNumArray SD(env,J);     // max shut-down rate
		IloNumArray SU(env,J);     // max start-up rate
		IloNumArray Sj(env,J);     // start-up segments	// for now all 1 segments
	//  cout<<"Sj"<<Sj<<endl;
	//	IloNumArray et(env,T);     // purchase price
	//	IloNumArray qt(env,T);     // sale price
	//	IloNumArray dtmin(env,T);  // min demand
	//	IloNumArray dtmax(env,T);  // max demand
		IloNumArray x(env,L);	// susceptance
		IloNumArray Rt(env,T+1);	// spinning reserve at time t
		IloNumArray Dt(env,T+1);	// total demand at time t
		IloNumArray Pl(env,L);	// maximum flow on line
		IloNumArray Gloc(env,J) ;	// generation location
//-------------unc demand
	//	NumVarMatrix  ucd(env,N);
	//	BoolVarMatrix card(env,N);
		IntMatrix line(env,L);      // trans lines
		NumMatrix dnt(env, N);     // dnt
		NumMatrix dpnt(env, N);    //dpnt
		IloInt lazcount=0;

			for(IloInt n=0;n<N;n++){
				dnt[n]=IloNumArray(env,T+1);
			}
			for(IloInt n=0;n<N;n++){
				dpnt[n]=IloNumArray(env,T+1);
			}
// kjt
			for(IloInt j=0;j<J;j++){
				Kjt[j]=IloNumArray(env,T+1);
			}
		NumMatrix Ustar(env, J);     // Ustar,output
			for(IloInt j=0;j<J;j++){
				Ustar[j]=IloNumArray(env,T+1);
			}
//		IntMatrix line(env,L);      // trans lines
		   for(IloInt l = 0; l < L; l++){
				line[l] = IloIntArray(env,2);
			}
		IloInt Betn = 6;
		IntMatrix cut(env, Betn);      // cut trans lines
		   for(IloInt l = 0; l < Betn; l++){
				cut[l] = IloIntArray(env,2);
			}
		IloBoolArray label(env, N);
		IloInt Betn1 = 4;
		IntMatrix cut1(env, Betn1);      // cut trans lines
		   for(IloInt l = 0; l < Betn1; l++){
				cut1[l] = IloIntArray(env,2);
			}
		IloBoolArray label1(env, N);
		IloInt Betn2 = 12;
		IntMatrix cut2(env, Betn2);      // cut trans lines
		   for(IloInt l = 0; l < Betn2; l++){
				cut2[l] = IloIntArray(env,2);
			}
		IloIntArray label2(env, N);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/Sj.txt", Sj, J);
			for(IloInt j=0;j<J;j++){
				Csu[j]=IloNumArray(env,Sj[j]);
			}
			for(IloInt j=0;j<J;j++){
				Tsu[j]=IloNumArray(env,Sj[j]);
			}
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/rj.txt", rj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/cj.txt", cj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/Gj.txt", Gj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/uj0.txt", uj0, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/G0.txt", G0, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/Gjb.txt", Gjb, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/Dj.txt", Dj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/Uj.txt", Uj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/RU.txt", RU, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/RD.txt", RD, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/UT.txt", UT, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/DT.txt", DT, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/UT0.txt", UT0, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/DT0.txt", DT0, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/SD.txt", SD, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/SU.txt", SU, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/Sj.txt", Sj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/Gloc.txt", Gloc, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/Rt.txt", Rt, T+1);
		readMaData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/Csu.txt", Csu, J, 2);
		readMaData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/Tsu.txt", Tsu, J, 2);
		readMaData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/dnt.txt", dnt, N, T+1);
		readIntMaData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/transmission.txt", line, L, 2);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/flowlimit.txt",Pl, L);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters1/reactance.txt", x, L);
		Md=0;
		for(IloInt t = 1; t <= T; t++){
			Dt[t]=0;
			for(IloInt n = 0; n < N; n++){
				Dt[t]+=dnt[n][t];
				Md+=dnt[n][t];
				}
			}
		Md=IloMax(Dt);
		for(IloInt t = 0; t <= T; t++)
			for(IloInt n = 0; n < N; n++)
				dpnt[n][t]= uncd*dnt[n][t];
cout<<"parameter initialization done"<<endl;
ofstream results("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/results2.txt");
ofstream Duals("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/duals2.txt");
ofstream flows("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/flows2.txt");
ofstream ccgresults("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/ccg2.txt",ios::app);

//$$$$$$$$$$$$$$$$$$$$ Overall Sub problem $$$$$$$$$$$$$$$$$$$$$$//
   NumMatrix gcstar(lazenv,J);
	for(IloInt j=0;j<J;j++){gcstar[j]=IloNumArray(lazenv,T+1);}
	for(IloInt j=0;j<J;j++)
	  for(IloInt t = 0; t <= T; t++)
		  gcstar[j][t]=0;
	IloInt itrc = 10;
	ThreeDNumMatrix Zntstar(lazenv,itrc);
		{ for(IloInt it = 0; it < itrc; it++)
			   Zntstar[it] = NumMatrix(lazenv,N);
		 for(IloInt it = 0; it < itrc; it++)
				for(IloInt n = 0; n < N; n++)
					Zntstar[it][n] = IloNumArray(lazenv,T+1); }
	for(IloInt it = 0; it < 2; it++)
		for(IloInt n = 0; n < N; n++)
			for(IloInt t = 0; t <= T; t++)
				Zntstar[it][n][t] = 0;
// ccg master problem variable
	NumVarMatrix gc(lazenv,J);
	  for(IloInt j=0;j<J;j++){gc[j]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}
	ThreeDVarMatrix pc(lazenv,itrc);
		  for(IloInt it = 0; it < itrc; it++)
			  pc[it] = NumVarMatrix(lazenv,L);
		  for(IloInt it = 0; it < itrc; it++)
				for(IloInt l = 0; l < L; l++)
					pc[it][l] = IloNumVarArray(lazenv,T+1, -IloInfinity, IloInfinity);
	ThreeDVarMatrix deltac(lazenv,itrc);
		  for(IloInt it = 0; it < itrc; it++)
			  deltac[it] = NumVarMatrix(lazenv,N);
		  for(IloInt it = 0; it < itrc; it++)
				for(IloInt n = 0; n < N; n++)
					deltac[it][n] = IloNumVarArray(lazenv,T+1, -IloInfinity, IloInfinity);
	ThreeDVarMatrix dc(lazenv,itrc);
		  for(IloInt it = 0; it < itrc; it++)
			  dc[it] = NumVarMatrix(lazenv,N);
		  for(IloInt it = 0; it < itrc; it++)
				for(IloInt n = 0; n < N; n++)
					dc[it][n] = IloNumVarArray(lazenv,T+1, 0, IloInfinity);
	ThreeDVarMatrix sc(lazenv,itrc);
		  for(IloInt it = 0; it < itrc; it++)
			  sc[it] = NumVarMatrix(lazenv,N);
		  for(IloInt it = 0; it < itrc; it++)
				for(IloInt n = 0; n < N; n++)
					sc[it][n] = IloNumVarArray(lazenv,T+1, 0, IloInfinity);
	IloNum lb_sub = -IloInfinity;
	IloNum ub_sub =  IloInfinity;
	IloNum ingap = 1;
	IloNumVar eta(lazenv,-IloInfinity,IloInfinity);
	IloModel maspc(lazenv);
	maspc.add(IloMinimize(lazenv,eta));
//** ccg master cconstraints**
for(IloInt j=0; j<J; j++){
	maspc.add(gc[j][0]==0);
	}
for(IloInt j=0; j<J; j++)
	for(IloInt t=1; t<=T; t++){
		maspc.add(gc[j][t-1]-gc[j][t] <= RD[j]*laz_u[j][t]+SD[j]*laz_w[j][t]); //Ramping down----traditional
		}
for(IloInt j=0; j<J; j++)
	for(IloInt t=1; t<=T; t++){
		maspc.add(gc[j][t]-gc[j][t-1] <= RU[j]*laz_u[j][t-1]+SU[j]*laz_v[j][t]); //Ramping Up----traditional
		}
for(IloInt j=0; j<J; j++)
	for(IloInt t= 1; t <= T; t++){
			maspc.add(gc[j][t]>=laz_u[j][t]*Gj[j]); //......Generation lower bound limit
			maspc.add(gc[j][t]<=laz_u[j][t]*Gjb[j]);
			}
try {
	IloCplex ccg_mas1(lazenv);
	ccg_mas1.extract(maspc);
	ccg_mas1.exportModel("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/uc_ccg_mas1.lp") ;
	cout<<"model exported"<<endl;
	ccg_mas1.end();
//*********************************
itrc=0;
ingap=1;
time_t begin,end;
begin = clock();
	while(ingap>=in_tlrn)
	 {
	 itrc++;
//......Transmission Network Constraints.
	for(IloInt l = 0; l < L; l++)
		 for(IloInt t = 1; t <= T; t++)  {
				maspc.add(pc[itrc][l][t]>=-Pl[l]);
				maspc.add(pc[itrc][l][t]<=Pl[l]);
		 }
  {for(IloInt t= 1; t <= T; t++)
	 for(IloInt n=0; n< N;n++)
	 {
		 maspc.add(dc[itrc][n][t]<=dnt[n][t]+Zntstar[itrc][n][t]*dpnt[n][t]);
		 maspc.add(deltac[itrc][n][t]<=maxdelta);
		 maspc.add(deltac[itrc][n][t]>=-maxdelta);
	 }}
  //......For L lines, DC power flow.
  { for(IloInt l=0; l<L;l++){
	  int m=line[l][0]; //origin bus
	  int r=line[l][1]; //destination bus
	  for(IloInt t= 1; t <= T; t++)
		 {
		 maspc.add(pc[itrc][l][t]*x[l]==100*(deltac[itrc][line[l][0]][t]-deltac[itrc][line[l][1]][t]));
		  }}}
//......load Balancing constraints, for each bus.
   for(IloInt t= 1; t <= T; t++)
	for(IloInt n= 0; n < N; n++)
		{IloExpr exp60c(lazenv);
		 IloExpr exp70c(lazenv);
		 IloExpr exp80c(lazenv);
		{for(IloInt i= 0; i < J; i++)
		{
			if(Gloc[i]==n){
				exp60c+=gc[i][t];
				}
		}}
	   {for(IloInt l = 0; l < L; l++)
		{
				if(line[l][1]==n)  // D(l)
					exp70c+=pc[itrc][l][t];
				else if(line[l][0]==n) // O(l)
					exp80c+=pc[itrc][l][t];
	   }}
		maspc.add(exp60c+exp70c-exp80c+dc[itrc][n][t]-sc[itrc][n][t] >= dnt[n][t]+Zntstar[itrc][n][t]*dpnt[n][t]); //load shed allowed
		maspc.add(sc[itrc][n][t] <= exp60c);
		maspc.add(dc[itrc][n][t] <= dnt[n][t]+Zntstar[itrc][n][t]*dpnt[n][t]);
		exp60c.end();
		exp70c.end();
		exp80c.end();
	}//end n
// generation greater than demand
   for(IloInt t=1; t<=T; t++) {
		IloExpr expsr1(lazenv);
		for(IloInt j=0; j<J; j++){
			expsr1+=gc[j][t];
			}
//		maspc.add(expsr1 >= Dt[t]);
		expsr1.end();
		}
IloExpr submasobjc(lazenv);
   for(IloInt j=0; j<J; j++)
		for(IloInt t=1; t<=T; t++){
			submasobjc+=cj[j]*gc[j][t];
		}
   for(IloInt t=1; t<=T; t++)
	   for(IloInt n= 0; n < N; n++){
		   submasobjc+=ldpen*dc[itrc][n][t];
		   submasobjc-=sellprice*sc[itrc][n][t];
		   }
maspc.add(eta>=submasobjc);
submasobjc.end();

IloCplex ccg_mas(lazenv);
ccg_mas.extract(maspc);
//	ccg_mas.exportModel("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/uc_ccg_mas.lp") ;
	ccg_mas.setParam(IloCplex::MIPSearch,solver_opt);  //1, traditional branch & cut
	if(presol==0){
	ccg_mas.setParam(IloCplex::PreInd,false);
		}
	ccg_mas.setParam(IloCplex::EpGap, sol_gap);
	if (!ccg_mas.solve()) {
		lazenv.error() << "Failed to solve ccg mas model" << endl;
		throw(-1);
		}
	cout<<"ccg mas obj: "<<ccg_mas.getObjValue()<<endl;
	cout<<"obj: "<<costuvw+ccg_mas.getObjValue()<<endl;
//	cout<<" diff: "<<obj_val-costuvw - ccg_mas.getObjValue()<<endl;
//  update
	for(IloInt t = 0; t <= T; t++)
		for(IloInt j= 0; j < J; j++){
			gcstar[j][t]=ccg_mas.getValue(gc[j][t]);
//		ccgresults<<""<<gcstar[j][t]<<endl;
			}
	lb_sub = ccg_mas.getObjValue(); // best feasible for LB
	ingap = abs((ub_sub -lb_sub)/ub_sub) ;
	end=clock();
	runningtime=double(end-begin)/CLOCKS_PER_SEC;
	ccgresults<<"iteration: "<<itrc<<" ccg_lb: "<<lb_sub<<" ccg_ub: "<<ub_sub<<" gap: "<<ingap<<" time:"<<runningtime<<endl;
	ccg_mas.end();
	if(ingap<in_tlrn) break;
//***************************CCG sub problem*******************************
	BoolVarMatrix zc(lazenv, N);	 //pi5lt
	  for(IloInt n=0;n<N;n++){zc[n]=IloBoolVarArray(lazenv,T+1);}
	NumVarMatrix pi5c(lazenv, L);	 //pi5lt
	  for(IloInt l=0;l<L;l++){pi5c[l]=IloNumVarArray(lazenv,T+1,-IloInfinity,IloInfinity);}
	NumVarMatrix pi6c(lazenv, N);	 //p6nt
	  for(IloInt n=0;n<N;n++){pi6c[n]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}
	NumVarMatrix pi6ac(lazenv, N);	 //p6nt
	  for(IloInt n=0;n<N;n++){pi6ac[n]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}
	NumVarMatrix pi7c(lazenv, L);	 //pi7lt
	  for(IloInt l=0;l<L;l++){pi7c[l]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}
	NumVarMatrix pi8c(lazenv, L);	 //pi8lt
	  for(IloInt l=0;l<L;l++){pi8c[l]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}
	NumVarMatrix pi9c(lazenv, N);	 //p9nt
	  for(IloInt n=0;n<N;n++){pi9c[n]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}
	NumVarMatrix pi10c(lazenv, N);	 //p10nt
	  for(IloInt n=0;n<N;n++){pi10c[n]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}
	NumVarMatrix pi11c(lazenv, N);	 //p11nt
	  for(IloInt n=0;n<N;n++){pi11c[n]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}
	NumVarMatrix pi12c(lazenv, N);	 //p11nt
	  for(IloInt n=0;n<N;n++){pi12c[n]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}
	NumVarMatrix beta1c(lazenv, N);	 //linearization
	  for(IloInt n=0;n<N;n++){beta1c[n]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}
	NumVarMatrix beta2c(lazenv, N);	 //linearization
	  for(IloInt n=0;n<N;n++){beta2c[n]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}
	NumVarMatrix beta3c(lazenv, N);	 //linearization
	  for(IloInt n=0;n<N;n++){beta3c[n]=IloNumVarArray(lazenv,T+1,0,IloInfinity);}

//* separate sub problem over time
IloNumArray	  ccgsubobjv(lazenv,T+1);
{for(IloInt t = 1; t <=T; t++)
	{
	IloModel subpc(lazenv);
	Md=ldpen;
	{for(IloInt n = 0; n < N; n++)	//dnt
	for(IloInt it=1; it<=itrc; it++){
			subpc.add(beta1c[n][t] <= pi6c[n][t]);
//			subpc.add(beta2c[n][t] <= pi6ac[n][t]);
			subpc.add(beta3c[n][t] <= pi11c[n][t]);
			subpc.add(beta1c[n][t] <= Md*zc[n][t]);
//			subpc.add(beta2c[n][t] <= Md*zc[n][t]);
			subpc.add(beta3c[n][t] <= Md*zc[n][t]);
			subpc.add(beta1c[n][t] >= Md*zc[n][t]+pi6c[n][t]-Md);
//			subpc.add(beta2c[n][t] >= Md*zc[n][t]+pi6ac[n][t]-Md);
			subpc.add(beta3c[n][t] >= Md*zc[n][t]+pi11c[n][t]-Md);
			}}
IloExpr subobjc(lazenv); //&&&& obj function
	{for(IloInt l = 0; l < L; l++){
		subobjc += (-Pl[l]*(pi7c[l][t]+pi8c[l][t]));
			}}
	{for(IloInt n = 0; n < N; n++){
		subobjc += -maxdelta*(pi9c[n][t]+pi10c[n][t]);
//		subobjc +=  dnt[n][t]*(pi6c[n][t]-pi6ac[n][t]-pi11c[n][t]);
//		subobjc +=  dpnt[n][t]*(beta1c[n][t]-beta2c[n][t]-beta3c[n][t]);
		subobjc +=  dnt[n][t]*(pi6c[n][t]-pi11c[n][t]);
		subobjc +=  dpnt[n][t]*(beta1c[n][t]-beta3c[n][t]);
			}}
IloNum locgc=0;
	{for(IloInt n = 0; n < N; n++){
			locgc = 0 ;
			for(IloInt i= 0; i < J; i++){
				if(Gloc[i]==n)
					locgc+=gcstar[i][t];}
//			subobjc += -locgc*(pi6c[n][t]-pi6ac[n][t]+pi12c[n][t]);
			subobjc += -locgc*(pi6c[n][t]+pi12c[n][t]);
			}}
	IloNum totalgstar = 0;
	{for(IloInt j= 0; j < J; j++){
			totalgstar += cj[j]*gcstar[j][t];
			}}
	subpc.add(IloMaximize(lazenv,subobjc+totalgstar));
	subobjc.end();
//--------- dual constraints
		IloInt lm;
		IloInt lr;
	{for(IloInt l = 0; l < L; l++) // plt
		{
			lm=line[l][0];
			lr=line[l][1];
//			subpc.add((x[l]/100)*pi5c[l][t]-pi6c[lm][t]+pi6ac[lm][t]
//			+pi6c[lr][t]-pi6ac[lr][t]+pi7c[l][t]-pi8c[l][t] == 0);
			subpc.add((x[l]/100)*pi5c[l][t]-pi6c[lm][t]+pi6c[lr][t]+pi7c[l][t]-pi8c[l][t] == 0);
			}}
	{for(IloInt n = 0; n < N; n++)	// delta nt
		{
		IloExpr isexpr1(lazenv);
		IloExpr isexpr2(lazenv);
		 for(IloInt l = 0; l < L; l++){
			if(line[l][1]==n)  // D(l)
			{
					isexpr1+= pi5c[l][t];
			}//end if
			if(line[l][0]==n)  // O(l)
			{
					isexpr2+= -pi5c[l][t];
			} //end if
		}//end for l
		subpc.add(isexpr2+isexpr1+pi9c[n][t]-pi10c[n][t]==0);
		isexpr1.end();
		isexpr2.end();
		}}
	{for(IloInt n = 0; n < N; n++)	//dnt
		{ //subpc.add(pi6c[n][t]-pi6ac[n][t]-pi11c[n][t]<=ldpen);
			subpc.add(pi6c[n][t]-pi11c[n][t]<=ldpen);}}

	{for(IloInt n = 0; n < N; n++)	//snt
		{//subpc.add(-pi6c[n][t]+pi6ac[n][t]-pi12c[n][t]<=-sellprice);
		 subpc.add(-pi6c[n][t]-pi12c[n][t]<=-sellprice);}}

	IloExpr bugc(lazenv);
	   {for(IloInt n = 0; n < N; n++){
			bugc += zc[n][t];}
		subpc.add(bugc<=uncdbug);} // budget on demand uncertainty
		bugc.end();

// update with fixing info
for(IloInt n = 0; n < N; n++)
	{	if(Z[n][t]==0){
		subpc.add(zc[n][t]==0);
		cout<<"Znt"<<n<<t<<"=0"<<endl;}
		if(Z[n][t]==1){
			subpc.add(zc[n][t]==1);
			cout<<"Znt"<<n<<t<<"=1"<<endl;
			}
		}

	IloCplex ccg_subpc(subpc);
	ccg_subpc.exportModel("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/uc_ccgsub.lp") ;
	ccg_subpc.setParam(IloCplex::MIPSearch,solver_opt);  //1, traditional branch & cut
	ccg_subpc.setParam(IloCplex::EpGap, sol_gap);
		if(presol==0){
	ccg_subpc.setParam(IloCplex::PreInd,false);
		}
	if (!ccg_subpc.solve()) {
		lazenv.error() << "Failed to solve sub model" << endl;
		throw(-1);
		}
	//update
		{for(IloInt n= 0; n < N; n++){
			Zntstar[itrc+1][n][t]=ccg_subpc.getValue(zc[n][t]);
		}}
	ccgsubobjv[t] = ccg_subpc.getObjValue();//taking 2% gap into consideration
	cout<<ccg_subpc.getObjValue()<<" "<<ccg_subpc.getCutoff()<<endl;
	ccg_subpc.end();
	subpc.end();
}} // END t, decomposed

double ub_sub_current = 0;
{for(IloInt t = 1; t < T+1; t++){
		ub_sub_current += ccgsubobjv[t];
	}}
ub_sub = IloMin(ub_sub,ub_sub_current); // best feasible for UB
	ingap = (ub_sub -lb_sub )/ub_sub ;
	cout<<"ccg sub obj: "<<ub_sub<<endl;
	cout<<"ccg LB: "<<lb_sub<<endl;
//	cout<<"obj: "<<stcost+ub_sub<<endl;
	cout<<"ingap: "<<ingap<<endl;
	end=clock();
	runningtime=double(end-begin)/CLOCKS_PER_SEC;
	ccgresults<<"iteration: "<<itrc<<" ccg_lb: "<<lb_sub<<" ccg_ub: "<<ub_sub<<" gap: "<<ingap<<" time: "<<runningtime<<endl;
 }//end while
 IloNum objtgc = 0;
 {for(IloInt t = 1; t < T+1; t++)
  for(IloInt j = 0; j < J; j++){
	  objtgc+=cj[j]*gcstar[j][t];
	  }}
  ccgresults<<"total gencost: "<<objtgc<<endl;
  ccgresults<<"load shed: "<<(lb_sub-objtgc)/ldpen<<endl;
  maspc.end();
  end=clock();
  runningtime=double(end-begin)/CLOCKS_PER_SEC;
  ccgresults<<"running time is "<<runningtime<<endl;

//************************* estimate Lower Bound *************
IloNum estlb = IloInfinity;
IloNum temUB = IloInfinity;
while(itrc>0)
	{
	itrc--;
	IloModel lbest(lazenv);
//** ccg master cconstraints**
for(IloInt j=0; j<J; j++){
	lbest.add(gc[j][0]==0);
	}
for(IloInt j=0; j<J; j++)
	for(IloInt t=1; t<=T; t++){
		lbest.add(gc[j][t-1]-gc[j][t] <= RD[j]*laz_u[j][t]+SD[j]*laz_w[j][t]); //Ramping down----traditional
		}
for(IloInt j=0; j<J; j++)
	for(IloInt t=1; t<=T; t++){
		lbest.add(gc[j][t]-gc[j][t-1] <= RU[j]*laz_u[j][t-1]+SU[j]*laz_v[j][t]); //Ramping Up----traditional
		}
for(IloInt j=0; j<J; j++)
	for(IloInt t= 1; t <= T; t++){
			lbest.add(gc[j][t]>=laz_u[j][t]*Gj[j]); //......Generation lower bound limit
			lbest.add(gc[j][t]<=laz_u[j][t]*Gjb[j]);
			}
//......Transmission Network Constraints.
	for(IloInt l = 0; l < L; l++)
		 for(IloInt t = 1; t <= T; t++)  {
				pc[0][l][t].setBounds(-Pl[l],Pl[l]);
				lbest.add(pc[0][l][t]>=-Pl[l]);
				lbest.add(pc[0][l][t]<=Pl[l]);
		 }
//......For L lines, DC power flow.
  {for(IloInt t= 1; t <= T; t++)
	 for(IloInt l=0; l<L;l++)
	 {
		 IloInt m,r;
		 m=line[l][0]; //origin bus
		 r=line[l][1]; //destination bus
		 lbest.add(pc[0][l][t]*x[l]==100*(deltac[0][m][t]-deltac[0][r][t]));
	 }}
  {for(IloInt t= 1; t <= T; t++)
	 for(IloInt n=0; n< N;n++)
	 {
		 lbest.add(dc[0][n][t]<=dnt[n][t]+Zntstar[itrc][n][t]*dpnt[n][t]);
		 lbest.add(deltac[0][n][t]<=maxdelta);
		 lbest.add(deltac[0][n][t]>=-maxdelta);
	 }}
//......load Balancing constraints, for each bus.
   for(IloInt t= 1; t <= T; t++)
	for(IloInt n= 0; n < N; n++)
		{IloExpr exp60c(lazenv);
		 IloExpr exp70c(lazenv);
		 IloExpr exp80c(lazenv);
		{for(IloInt i= 0; i < J; i++)
		{
			if(Gloc[i]==n){
				exp60c+=gc[i][t];
				}
		}}
	   {for(IloInt l = 0; l < L; l++)
		{
				if(line[l][1]==n)  // D(l)
					exp70c+=pc[0][l][t];
				else if(line[l][0]==n) // O(l)
					exp80c+=pc[0][l][t];
	   }}
		lbest.add(exp60c+exp70c-exp80c+dc[0][n][t]-sc[0][n][t] >= dnt[n][t]+Zntstar[itrc+2][n][t]*dpnt[n][t]); //load shed allowed
		lbest.add(sc[0][n][t] <= exp60c);
		lbest.add(dc[0][n][t] <= dnt[n][t]+Zntstar[itrc+2][n][t]*dpnt[n][t]);
		exp60c.end();
		exp70c.end();
		exp80c.end();
	}//end n

// generation greater than demand
IloExpr submasobjc(lazenv);
   for(IloInt j=0; j<J; j++)
		for(IloInt t=1; t<=T; t++){
			submasobjc+=cj[j]*gc[j][t];
		}
   for(IloInt t=1; t<=T; t++)
	   for(IloInt n= 0; n < N; n++){
		   submasobjc+=ldpen*dc[0][n][t];
		   submasobjc-=sellprice*sc[0][n][t];
		   }
lbest.add(IloMinimize(lazenv,submasobjc));
submasobjc.end();

IloCplex cplexlb(lbest);
//	cplexlb.exportModel("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/uc_ccg_mas.lp") ;
	cplexlb.setParam(IloCplex::MIPSearch,solver_opt);  //1, traditional branch & cut
		if(presol==0){
	cplexlb.setParam(IloCplex::PreInd,false);
		}
	cplexlb.setParam(IloCplex::EpGap, sol_gap);
	if (!cplexlb.solve()) {
		lazenv.error() << "Failed to solve lb estimation model" << endl;
		throw(-1);
		}
	cout<<"subp LB estimation: "<<cplexlb.getObjValue()<<endl;
	ccgresults<<"subp LB estimation: "<<cplexlb.getObjValue()<<endl;
	cout<<"obj: "<<costuvw+cplexlb.getObjValue()<<endl;
	ccgresults<<"obj: "<<costuvw+cplexlb.getObjValue()<<endl;
//update, pick the zstar with lowest LB
if(cplexlb.getObjValue()<estlb){
//	temUB = costuvw+cplexlb.getObjValue();
	for(IloInt t=1; t<=T; t++)
		for(IloInt n= 0; n < N; n++){
			Zoutstar[itrc_out][n][t]=Zntstar[itrc+2][n][t];
			Znode[n][t]=Zntstar[itrc+2][n][t]; // current best feasible solution
		}
	}
cplexlb.end();
lbest.end();
} //end innermost while
outUB = IloMin(costuvw+lb_sub,outUB);
outgap = (outUB-outLB)/outUB;
ccgresults<<"---outUB: "<<outUB<<" outGap: "<<outgap <<endl;
cout<<"good til"<<endl;
}// end try
	catch (IloException& ex){	  cerr << "Error: " << ex << endl;	}
	catch (...)				{	  cerr << "Error" << endl;			}
	lazenv.end();
//update bounds
UB = ub_sub;
LB = IloMax(lb_sub,LB);
cout<<"Node info: "<<"UB--"<<UB<<" LB--"<<LB<<endl;
return 0;
}//end ubcal
コード例 #12
0
ファイル: CAP_newM.cpp プロジェクト: tikhoncheva/work
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;
}
コード例 #13
0
ファイル: gotic.cpp プロジェクト: ed-d/Projet
ILOSTLBEGIN

int main(int argc, char** argv)
{
    IloEnv env ;

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

        // Get data                                                             
        // Import data from file
        try
        {
           //IloInt i, j ;

           const char* filename ;

           if (argc > 1)
              filename = argv[1] ;
           else
              filename = "data/tsp.dat" ;

           ifstream f(filename, ios::in) ;

            if (!f)
           {
              cerr << "No such file: " << filename << endl ;
              throw(1) ;
           }

        // Create data matrix
        IloArray<IloNumArray> costmatrix (env) ;
        f >> costmatrix ;
        IloInt n = costmatrix.getSize() ;

        // Define variables and "fill" them so as not to get seg faults
        IloArray<IloIntVarArray> x (env, n) ;
        for (i=0 ; i<n ; i++)
        {
            x[i] = IloIntVarArray (env, n) ;
            for(IloInt j=0 ; j<n ; j++)
            {
                x[i][j] = IloIntVar (env) ;
            }
        }

        IloIntVarArray u (env, n) ;
        for(i=0 ; i<n ; i++)
        {
            u[i] = IloIntVar (env) ;
        }

        // Define constraints
        IloExpr constr_i (env) ;
        IloExpr constr_j (env) ;
        IloExpr constr_u (env) ;
        
        // Vertical constraint
        // Create a full vector with a hole to express the vertical constraint as a scalar product
        IloIntArray basevector (env, n) ;
        basevector[0] = 0 ;
        for (int i=1 ; i<n ; i++)
        {
            basevector[i] = 1 ;
        }
        constr_i = IloScalProd(basevector, x[0]) ;
        model.add( constr_i == 1) ;

        for (i=1 ; i < n ; i++)
        {
            basevector[i-1] = 1 ;
            basevector[i] = 0 ;
            constr_i = IloScalProd(basevector, x[i]) ;
            model.add(constr_i == 1) ;

            for (j=0 ; j < n ; j++)
            {
               if (i != j)
               {
                  constr_j += x[j][i] ;
                  constr_u = u[i] - u[j] + n*x[i][j] ;
                  model.add(constr_u == 1) ;
               }
            }
            model.add(constr_j == 1) ;
        }


        // Define objective                                                     
        IloExpr obj (env) ;
        for (i=1 ; i < n ; i++)
        {
            for (j=0 ; j < n ; j++)
            {
               if (i != j)
               {
                  obj += costmatrix[i][j] * x[i][j] ;
               }
            }
        }                                             
        model.add( IloMinimize(env, obj) ) ;                                   

        // Extract model                                                        
        cplex.extract(model);

        // Export model                                                         

        // Set parameters                                                     

        // Solve                                                                
        if ( !cplex.solve() ) 
        {
            env.error() << "Failed to optimize problem" << endl;
            cplex.out() << "Solution status " << cplex.getStatus() << endl ;
            cplex.out() << "Model" << cplex.getModel() << endl ;
            throw(-1);
        }

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

        // Print solution details                                               

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

  }
  catch (...)
  {
      cerr << "Unknown exception caught" << endl ;
  }
    
  // freeing memory                                                           
  env.end();
  return 0;
} // END main         
コード例 #14
0
ファイル: lp.cpp プロジェクト: nikhilpb/wbm-admm
ILOSTLBEGIN
#include <unistd.h>
#include <math.h>

int
main (int argc, char **argv)
{
	int N = 5000;
	if (argc > 1){
		N = atoi(argv[1]);
	}
	double M = 100000;
  double** w = new double*[N];
	for (int i = 0; i < N; i++){
		w[i] = new double[N];
		for (int j = 0; j < N; j++){
			if (i == j){
				w[i][j] = i;
			} 
			else {
				w[i][j] = i-abs(i-j);
			}
		}
	} 
	
	IloEnv   env;
   try {
			IloModel model(env);
      
      IloNumVarArray xa(env);
			IloNumVarArray xi(env);
			
			for (int i = 0; i < N; i++){
				xa.add(IloNumVar(env));
				xi.add(IloNumVar(env));
			}
		
			IloNumExpr obj = xa[0] + xi[0];	
			
			for (int i = 1; i < N; i++){
				
				obj = obj + xa[i];
				obj = obj + xi[i];
			}	
			
      IloRangeArray con(env);
			for (int i = 0; i < N; i++){
				for (int j = 0; j < N; j++){
					con.add(xa[i] + xi[j] >= w[i][j]);
				}
			}
			
			model.add(con);
   		model.add(IloMinimize(env, obj));
			// populate model 
 
      IloCplex cplex(model);

      if ( !cplex.solve() ) {
         env.error() << "Failed to optimize LP" << endl;
         throw(-1);
      }
      env.out() << "Solution value  = " << cplex.getObjValue() << endl;
   }
   catch (IloException& e) {
      cerr << "Concert exception caught: " << e << endl;
   }
   catch (...) {
      cerr << "Unknown exception caught" << endl;
   }

   env.end();

   return 0;
}
コード例 #15
0
ファイル: subduality.cpp プロジェクト: tramelon/branchbound
int subduality(double &UB, double &LB, int U[][T1+1], int V[][T1+1], int W[][T1+1],float Znode[][T1+1], int budget, double costuvw)
	{

	IloInt m; // O(l),origin or line
	IloInt r; // D(l),destination of line
	IloNum scale=1; // nodal demand scale
	IloNum maxdelta= 1.57;
	double obj_val;
	IloNum subobjval;
	double ldpen=ldpena; // penalty for load shed
	IloInt uncdbug = budget;  // demand uncertain budget
	double uncd = uncda; // uncertainty part / demand 
	double in_tlrn = 0.005 ; // in gap torrence, 0.01
	double sol_gap = 0.001 ; // solver gap
	IloInt itrc_out = 0;
	IloInt res_itrc = 20;// initial set of scenarios in mas problem
	IloNum outgap = 1;
	IloNum outLB = -IloInfinity;
	IloNum outUB =  IloInfinity;
	double runningtime;
//	IloInt J=J;	//units
//	IloInt T=T1;	//time
//	IloInt N=Nn;    // buses
//	IloInt L=186;    // trans lines
	IloEnv env;
	
try{
// NumMatrix dnt(env);
		IloNum Md; // penalty for dual
		IloNum sellprice = 0;
		ThreeDBoolVarMatrix h(env,J); // start-up type
		IloNumVar beta(env, -IloInfinity,IloInfinity);
		NumMatrix Tsu(env, J);     // Tsu_gs
		NumMatrix Csu(env, J);     // Csu_gs
		NumMatrix Kjt(env, J);
		IloNumArray aj(env,J);    // no loads cost
		IloNumArray rj(env,J);    //
		IloNumArray cj(env,J);    // linear variable cost
		IloNumArray Gj(env,J);    // min output
		IloNumArray G0(env,J);    // Initial output
		IloNumArray Gjb(env,J);    // max output
		IloNumArray Dj(env,J); 	// number of hours j required to be off at the start period
		IloNumArray Uj(env,J); 	// number of hours j required to be up at the start period
		IloNumArray uj0(env,J);     //initial status of gen
		IloNumArray gj0(env,J);     //initial status of gen
		for(IloInt j=0; j<J; j++){
			gj0[j]=0;
			}
		IloNumArray RU(env,J); 	// ramping up
		IloNumArray RD(env,J); 	// ramping down
		IloNumArray UT(env,J);     // min up
		IloNumArray UT0(env,J);    // online time before schedule
		IloNumArray UTr(env,J);    //
		IloNumArray DT(env,J);     // min down
		IloNumArray DT0(env,J);    // offline time before schedule
		IloNumArray DTr(env,J);    //
		IloNumArray SD(env,J);     // max shut-down rate
		IloNumArray SU(env,J);     // max start-up rate
		IloNumArray Sj(env,J);     // start-up segments	// for now all 1 segments
	//  cout<<"Sj"<<Sj<<endl;
	//	IloNumArray et(env,T);     // purchase price
	//	IloNumArray qt(env,T);     // sale price
	//	IloNumArray dtmin(env,T);  // min demand
	//	IloNumArray dtmax(env,T);  // max demand
		IloNumArray x(env,L);	// susceptance
		IloNumArray Rt(env,T+1);	// spinning reserve at time t
		IloNumArray Dt(env,T+1);	// total demand at time t
		IloNumArray Pl(env,L);	// maximum flow on line
		IloNumArray Gloc(env,J) ;	// generation location
//-------------unc demand
	//	NumVarMatrix  ucd(env,N);
	//	BoolVarMatrix card(env,N);
		IntMatrix line(env,L);      // trans lines
		NumMatrix dnt(env, N);     // dnt
		NumMatrix dpnt(env, N);    //dpnt
		IloInt lazcount=0;

			for(IloInt n=0;n<N;n++){
				dnt[n]=IloNumArray(env,T+1);
			}
			for(IloInt n=0;n<N;n++){
				dpnt[n]=IloNumArray(env,T+1);
			}
// kjt
			for(IloInt j=0;j<J;j++){
				Kjt[j]=IloNumArray(env,T+1);
			}
		NumMatrix Ustar(env, J);     // Ustar,output
			for(IloInt j=0;j<J;j++){
				Ustar[j]=IloNumArray(env,T+1);
			}
//		IntMatrix line(env,L);      // trans lines
		   for(IloInt l = 0; l < L; l++){
				line[l] = IloIntArray(env,2);
			}
		IloIntArray label2(env, N);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/Sj.txt", Sj, J);
			for(IloInt j=0;j<J;j++){
				Csu[j]=IloNumArray(env,Sj[j]);
			}
			for(IloInt j=0;j<J;j++){
				Tsu[j]=IloNumArray(env,Sj[j]);
			}
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/aj.txt", aj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/rj.txt", rj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/cj.txt", cj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/Gj.txt", Gj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/uj0.txt", uj0, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/G0.txt", G0, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/Gjb.txt", Gjb, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/Dj.txt", Dj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/Uj.txt", Uj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/RU.txt", RU, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/RD.txt", RD, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/UT.txt", UT, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/DT.txt", DT, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/UT0.txt", UT0, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/DT0.txt", DT0, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/SD.txt", SD, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/SU.txt", SU, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/Sj.txt", Sj, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/Gloc.txt", Gloc, J);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/Rt.txt", Rt, T+1);
		readMaData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/Csu.txt", Csu, J, 2);
		readMaData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/Tsu.txt", Tsu, J, 2);
		readMaData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/dnt.txt", dnt, N, T+1);
		readIntMaData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/transmission.txt", line, L, 2);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/flowlimit.txt",Pl, L);
		readData ("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/parameters/reactance.txt", x, L);
		Md=0;
		for(IloInt t = 1; t <= T; t++){
			Dt[t]=0;
			for(IloInt n = 0; n < N; n++){
				Dt[t]+=dnt[n][t];
				Md+=dnt[n][t];
				}
			}
		Md=IloMax(Dt);
		for(IloInt t = 0; t <= T; t++)
			for(IloInt n = 0; n < N; n++)
				dpnt[n][t]= uncd*dnt[n][t];

ofstream results("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/results1.txt");
ofstream Duals("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/duals1.txt");
ofstream flows("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/flows1.txt");
ofstream ccgresults("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/ccg1.txt",ios::app);

BoolVarMatrix znt(env,N);
	  for(IloInt n=0;n<N;n++){znt[n]=IloBoolVarArray(env,T+1);}
	NumVarMatrix beta1(env, N);	 //linearization
	  for(IloInt n=0;n<N;n++){beta1[n]=IloNumVarArray(env,T+1,0,IloInfinity);}
	NumVarMatrix beta2(env, N);	 //linearization
	  for(IloInt n=0;n<N;n++){beta2[n]=IloNumVarArray(env,T+1,0,IloInfinity);}	
	NumVarMatrix beta3(env, N);	 //linearization
	  for(IloInt n=0;n<N;n++){beta3[n]=IloNumVarArray(env,T+1,0,IloInfinity);}
	NumVarMatrix q(env, N);	 //uncertain demand
	  for(IloInt n=0;n<N;n++){q[n]=IloNumVarArray(env,T+1,0,IloInfinity);}
	BoolVarMatrix z(env, N);	 //uncertain demand
	  for(IloInt n=0;n<N;n++){z[n]=IloBoolVarArray(env,T+1);}
	NumVarMatrix pi1(env, J);	 //p1jt
	  for(IloInt j=0;j<J;j++){pi1[j]=IloNumVarArray(env,T+1,0,IloInfinity);}   	
	NumVarMatrix pi2(env, J);	 //p2jt
	  for(IloInt j=0;j<J;j++){pi2[j]=IloNumVarArray(env,T+1,0,IloInfinity);}
	NumVarMatrix pi3(env, J);	 //p3jt
	  for(IloInt j=0;j<J;j++){pi3[j]=IloNumVarArray(env,T+1,0,IloInfinity);}
	NumVarMatrix pi4(env, J);	 //p4jt
	  for(IloInt j=0;j<J;j++){pi4[j]=IloNumVarArray(env,T+1,0,IloInfinity);}
	NumVarMatrix pi5(env, L);	 //pi5lt
	  for(IloInt l=0;l<L;l++){pi5[l]=IloNumVarArray(env,T+1,-IloInfinity,IloInfinity);}
	NumVarMatrix pi6(env, N);	 //p6nt
	  for(IloInt n=0;n<N;n++){pi6[n]=IloNumVarArray(env,T+1,-IloInfinity,IloInfinity);}	   
	NumVarMatrix pi7(env, L);	 //pi7lt
	  for(IloInt l=0;l<L;l++){pi7[l]=IloNumVarArray(env,T+1,0,IloInfinity);}
	NumVarMatrix pi8(env, L);	 //pi8lt
	  for(IloInt l=0;l<L;l++){pi8[l]=IloNumVarArray(env,T+1,0,IloInfinity);}
	NumVarMatrix pi9(env, N);	 //p9nt
	  for(IloInt n=0;n<N;n++){pi9[n]=IloNumVarArray(env,T+1,0,IloInfinity);}
	NumVarMatrix pi10(env, N);	 //p10nt
	  for(IloInt n=0;n<N;n++){pi10[n]=IloNumVarArray(env,T+1,0,IloInfinity);}
	NumVarMatrix pi11(env, N);	 //p11nt
	  for(IloInt n=0;n<N;n++){pi11[n]=IloNumVarArray(env,T+1,0,IloInfinity);}
	IloNumVarArray  pi12(env,T+1,0,IloInfinity);
	IloNumVarArray  pi14(env,T+1,0,IloInfinity);
	NumVarMatrix mq(env, N);	 // linearization 
	  for(IloInt n=0;n<N;n++){mq[n]=IloNumVarArray(env,T+1,0,IloInfinity);}	
//--------------obj func
	  IloExpr subobj(env);
	for(IloInt l = 0; l < L; l++)
		for(IloInt t = 1; t <= T; t++){
		subobj += (-Pl[l]*(pi7[l][t]+pi8[l][t]));
		}		
	for(IloInt n = 0; n < N; n++)
		for(IloInt t = 1; t <= T; t++){
//		subobj += (-maxdelta*(pi9[n][t]+pi10[n][t])+dnt[n][t]*(pi6[n][t]-pi11[n][t]));
		subobj += (-maxdelta*(pi9[n][t]+pi10[n][t])+dnt[n][t]*(pi6[n][t]-pi11[n][t]))+dpnt[n][t]*(beta1[n][t]-beta2[n][t]);
		}	
	for(IloInt j = 0; j < J; j++)
		for(IloInt t = 1; t <= T; t++){
		subobj += (-(RD[j]*U[j][t]+SD[j]*W[j][t])*pi1[j][t]-(RU[j]*U[j][t-1]+SU[j]*V[j][t])*pi2[j][t]);
		subobj += Gj[j]*U[j][t]*pi3[j][t]-Gjb[j]*U[j][t]*pi4[j][t];
		if(t==1){
			subobj += gj0[j]*(pi1[j][t] -pi2[j][t]);
		}
	}
	for(IloInt t = 1; t <= T; t++){
//		subobj+= Dt[t]*pi12[t];
		}
	for(IloInt n = 0; n < N; n++)
		for(IloInt t = 1; t <= T; t++){
			subobj+= dnt[n][t]*pi14[t]+dpnt[n][t]*beta3[n][t];
			}
	IloModel subp(env);
	subp.add(IloMaximize(env,subobj));
	subobj.end();
//---------constraints---------------------------//
//------- linearization constraints

	for(IloInt t = 1; t <= T; t++){
		IloExpr subbug(env);
		for(IloInt n = 0; n < N; n++){
			subp.add(znt[n][t]>=0);
			subbug += znt[n][t];} 
		subp.add(subbug<=uncdbug); // budget on demand uncertaint
		subbug.end();
		}
	Md=500;
	for(IloInt n = 0; n < N; n++)	//dnt
		for(IloInt t = 1; t <= T; t++){
			subp.add(beta1[n][t] <= pi6[n][t]);
			subp.add(beta2[n][t] <= pi11[n][t]);
			subp.add(beta3[n][t] <= pi14[t]);
			subp.add(beta1[n][t] <= Md*znt[n][t]);
			subp.add(beta2[n][t] <= Md*znt[n][t]);
			subp.add(beta3[n][t] <= Md*znt[n][t]);
			subp.add(beta1[n][t] >= Md*znt[n][t]+pi6[n][t]-Md);
			subp.add(beta2[n][t] >= Md*znt[n][t]+pi11[n][t]-Md);
			subp.add(beta3[n][t] >= Md*znt[n][t]+pi14[t]-Md);
			}	

//--------- dual constraints
	for(IloInt j = 0; j < J; j++)  // gjt
		for(IloInt t = 1; t <= T-1; t++){
			subp.add(pi1[j][t]-pi1[j][t+1]-pi2[j][t]+pi2[j][t+1]+pi3[j][t]-pi4[j][t]+pi6[Gloc[j]][t]/* + pi12[t]*/+ pi14[t]<= cj[j]);
		}
	for(IloInt j = 0; j < J; j++){
			subp.add(pi1[j][T]-pi2[j][T]+pi3[j][T]-pi4[j][T]+pi6[Gloc[j]][T]/*+ pi12[T]*/+ pi14[T]<= cj[j]);
		}
		IloInt lm;
		IloInt lr;
	for(IloInt l = 0; l < L; l++) // plt
		for(IloInt t = 1; t <= T; t++){
			lm=line[l][0];
			lr=line[l][1];
			subp.add((x[l]/100)*pi5[l][t]-pi6[lm][t]+pi6[lr][t]+pi7[l][t]-pi8[l][t] == 0);
		}
	for(IloInt n = 0; n < N; n++)	// delta nt
		for(IloInt t = 1; t <= T; t++){
		IloExpr iexpr1(env);
		IloExpr iexpr2(env);
		 for(IloInt l = 0; l < L; l++)
		{
			if(line[l][1]==n)  // D(l)
			{
					iexpr1+= pi5[l][t];
			}//end if
			if(line[l][0]==n)  // O(l)
			{
					iexpr2+= -pi5[l][t];
			} //end if
		}//end for l
		subp.add(iexpr2+iexpr1+pi9[n][t]-pi10[n][t]==0);
		iexpr1.end();
		iexpr2.end();
		}
	for(IloInt n = 0; n < N; n++)	//dnt
		for(IloInt t = 1; t <= T; t++){
			subp.add(pi6[n][t]-pi11[n][t]<=ldpen);
		}
	IloCplex cplex_sub(subp);
	
	if(presol==0){
	cplex_sub.setParam(IloCplex::PreInd,false);
		}
//	cplex_sub.exportModel("C:/Dropbox/Robust_UC_ISONE/data/118bus/iit/results/uc_sub.lp") ;
	cplex_sub.setParam(IloCplex::EpGap, 0.005);
	cplex_sub.setParam(IloCplex::MIPSearch,0);  //1, traditional branch & cut
	if (!cplex_sub.solve()) {
		env.error() << "Failed to solve model" << endl;
		throw(-1);
		}
		
	subobjval = cplex_sub.getObjValue();
	cout<<"dual obj: "<<cplex_sub.getObjValue()<<endl;
	cout<<"obj: "<<costuvw+cplex_sub.getObjValue()<<endl;
//	cout<<" diff: "<<obj_val-costuvw- cplex_sub.getObjValue()<<endl;
if(costuvw+subobjval <= outUB){
	outUB = IloMin(costuvw+subobjval,outUB);
	outgap = (outUB-outLB)/outUB;
	ccgresults<<"---outUB: "<<outUB<<" outGap: "<<outgap <<endl;
	if(uncdbug>=1){
	for(IloInt t=1; t<=T; t++)
		for(IloInt n= 0;n<N;n++){
			Znode[n][t]=cplex_sub.getValue(z[n][t]); // current best feasible solution
			}}
	}

	cplex_sub.end();
	subp.end();
}// end try
	catch (IloException& ex){	  cerr << "Error: " << ex << endl;	}
	catch (...)				{	  cerr << "Error" << endl;			}
	env.end();
//update bounds
UB = subobjval;
LB = subobjval;
return 0;
}//end ubcal
コード例 #16
0
ファイル: eerstewerkend.cpp プロジェクト: ardgrauw/Thesis
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
コード例 #17
0
ファイル: ilosocpex1.cpp プロジェクト: renvieir/ioc
// Test KKT conditions on the solution.
// The function returns true if the tested KKT conditions are satisfied
// and false otherwise.
// The function assumes that the model currently extracted to CPLEX is fully
// described by obj, vars and rngs.
static bool
checkkkt (IloCplex& cplex, IloObjective const& obj, IloNumVarArray const& vars,
          IloRangeArray const& rngs, IloIntArray const& cone, double tol)
{
   IloEnv env = cplex.getEnv();
   IloModel model = cplex.getModel();
   IloNumArray x(env), dslack(env);
   IloNumArray pi(env, rngs.getSize()), slack(env);

   // Read primal and dual solution information.
   cplex.getValues(x, vars);
   cplex.getSlacks(slack, rngs);

   // pi for second order cone constraints.
   getsocpconstrmultipliers(cplex, vars, rngs, pi, dslack);

   // pi for linear constraints.
   for (IloInt i = 0; i < rngs.getSize(); ++i) {
      IloRange r = rngs[i];
      if ( !r.getQuadIterator().ok() )
         pi[idx(r)] = cplex.getDual(r);
   }

   // Print out the data we just fetched.
   streamsize oprec = env.out().precision(3);
   ios_base::fmtflags oflags = env.out().setf(ios::fixed | ios::showpos);
   env.out() << "x      = [";
   for (IloInt i = 0; i < x.getSize(); ++i)
      env.out() << " " << x[i];
   env.out() << " ]" << endl;
   env.out() << "dslack = [";
   for (IloInt i = 0; i < dslack.getSize(); ++i)
      env.out() << " " << dslack[i];
   env.out() << " ]" << endl;
   env.out() << "pi     = [";
   for (IloInt i = 0; i < rngs.getSize(); ++i)
      env.out() << " " << pi[i];
   env.out() << " ]" << endl;
   env.out() << "slack  = [";
   for (IloInt i = 0; i < rngs.getSize(); ++i)
      env.out() << " " << slack[i];
   env.out() << " ]" << endl;
   env.out().precision(oprec);
   env.out().flags(oflags);

   // Test primal feasibility.
   // This example illustrates the use of dual vectors returned by CPLEX
   // to verify dual feasibility, so we do not test primal feasibility
   // here.

   // Test dual feasibility.
   // We must have
   // - for all <= constraints the respective pi value is non-negative,
   // - for all >= constraints the respective pi value is non-positive,
   // - the dslack value for all non-cone variables must be non-negative.
   // Note that we do not support ranged constraints here.
   for (IloInt i = 0; i < vars.getSize(); ++i) {
      IloNumVar v = vars[i];
      if ( cone[i] == NOT_IN_CONE && dslack[i] < -tol ) {
         env.error() << "Dual multiplier for " << v << " is not feasible: "
                     << dslack[i] << endl;
         return false;
      }
   }
   for (IloInt i = 0; i < rngs.getSize(); ++i) {
      IloRange r = rngs[i];
      if ( fabs (r.getLB() - r.getUB()) <= tol ) {
         // Nothing to check for equality constraints.
      }
      else if ( r.getLB() > -IloInfinity && pi[i] > tol ) {
         env.error() << "Dual multiplier " << pi[i] << " for >= constraint"
                     << endl << r << endl
                     << "not feasible"
                     << endl;
         return false;
      }
      else if ( r.getUB() < IloInfinity && pi[i] < -tol ) {
         env.error() << "Dual multiplier " << pi[i] << " for <= constraint"
                     << endl << r << endl
                     << "not feasible"
                     << endl;
         return false;
      }
   }

   // Test complementary slackness.
   // For each constraint either the constraint must have zero slack or
   // the dual multiplier for the constraint must be 0. We must also
   // consider the special case in which a variable is not explicitly
   // contained in a second order cone constraint.
   for (IloInt i = 0; i < vars.getSize(); ++i) {
      if ( cone[i] == NOT_IN_CONE ) {
         if ( fabs(x[i]) > tol && dslack[i] > tol ) {
            env.error() << "Invalid complementary slackness for " << vars[i]
                        << ":" << endl
                        << " " << x[i] << " and " << dslack[i]
                        << endl;
            return false;
         }
      }
   }
   for (IloInt i = 0; i < rngs.getSize(); ++i) {
      if ( fabs(slack[i]) > tol && fabs(pi[i]) > tol ) {
         env.error() << "Invalid complementary slackness for "
                     << endl << rngs[i] << ":" << endl
                     << " " << slack[i] << " and " << pi[i]
                     << endl;
         return false;
      }
   }

   // Test stationarity.
   // We must have
   //  c - g[i]'(X)*pi[i] = 0
   // where c is the objective function, g[i] is the i-th constraint of the
   // problem, g[i]'(x) is the derivate of g[i] with respect to x and X is the
   // optimal solution.
   // We need to distinguish the following cases:
   // - linear constraints g(x) = ax - b. The derivative of such a
   //   constraint is g'(x) = a.
   // - second order constraints g(x[1],...,x[n]) = -x[1] + |(x[2],...,x[n])|
   //   the derivative of such a constraint is
   //     g'(x) = (-1, x[2]/|(x[2],...,x[n])|, ..., x[n]/|(x[2],...,x[n])|
   //   (here |.| denotes the Euclidean norm).
   // - bound constraints g(x) = -x for variables that are not explicitly
   //   contained in any second order cone constraint. The derivative for
   //   such a constraint is g'(x) = -1.
   // Note that it may happen that the derivative of a second order cone
   // constraint is not defined at the optimal solution X (this happens if
   // X=0). In this case we just skip the stationarity test.
   IloNumArray sum(env, vars.getSize());
   for (IloExpr::LinearIterator it = obj.getLinearIterator(); it.ok(); ++it)
      sum[idx(it.getVar())] = it.getCoef();

   for (IloInt i = 0; i < vars.getSize(); ++i) {
      IloNumVar v = vars[i];
      if ( cone[i] == NOT_IN_CONE )
         sum[i] -= dslack[i];
   }
   for (IloInt i = 0; i < rngs.getSize(); ++i) {
      IloRange r = rngs[i];
      if ( r.getQuadIterator().ok() ) {
         // Quadratic (second order cone) constraint.
         IloNum norm = 0.0;
         for (IloExpr::QuadIterator q = r.getQuadIterator(); q.ok(); ++q) {
            if ( q.getCoef() > 0 )
               norm += x[idx(q.getVar1())] * x[idx(q.getVar1())];
         }
         norm = sqrt(norm);
         if ( fabs(norm) <= tol ) {
            // Derivative is not defined. Skip test.
            env.warning() << "Cannot test stationarity at non-differentiable point."
                          << endl;
            return true;
         }
         else {
            for (IloExpr::QuadIterator q = r.getQuadIterator(); q.ok(); ++q) {
               if ( q.getCoef() < 0 )
                  sum[idx(q.getVar1())] -= pi[i];
               else
                  sum[idx(q.getVar1())] += pi[i] * x[idx(q.getVar1())] / norm;
            }
         }
      }
      else {
         // Linear constraint.
         for (IloExpr::LinearIterator l = r.getLinearIterator(); l.ok(); ++l)
            sum[idx(l.getVar())] -= pi[i] * l.getCoef();
      }
   }

   // Now test that all elements in sum[] are 0.
   for (IloInt i = 0; i < vars.getSize(); ++i) {
      if ( fabs(sum[i]) > tol ) {
         env.error() << "Invalid stationarity " << sum[i] << " for "
                     << vars[i] << endl;
         return false;
      }
   }

   return true;   
}
コード例 #18
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
コード例 #19
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
コード例 #20
0
ファイル: instance.cpp プロジェクト: shidanxu/solver
 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();
 }
コード例 #21
0
ファイル: CAP_newOrder.cpp プロジェクト: tikhoncheva/work
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;
}
コード例 #22
0
ファイル: main.cpp プロジェクト: drhachmann/PLI_TP2
int
main (int argc, char **argv)
{
   IloEnv   env;
   try {
      IloModel model(env);

      if (( argc != 2 )                         ||
          ( argv[1][0] != '-' )                 ||
          ( strchr ("rcn", argv[1][1]) == NULL )   ) {
         usage (argv[0]);
         throw(-1);
      }

      IloIntVarArray var(env);
      IloRangeArray con(env);

      switch (argv[1][1]) {
         case 'r':
            populatebyrow (model, var, con);
            break;
         case 'c':
            populatebycolumn (model, var, con);
            break;
         case 'n':
            populatebynonzero (model, var, con);
            break;
      }

      IloCplex cplex(model);

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

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

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

   env.end();

   return 0;
}  // END main