Пример #1
0
IloNum DistHelper::dist( IloNum t)
{
    unsigned int sum=0;
    for(unsigned int i=0; i<Region->size(); ++i)
    {
        if(D((*Region)[i], *vox, *w) <= t) {
            ++sum;
        }
    }

    return IloNum(sum)/IloNum(Region->size());
}
void CPLEX_LP_IMSTSolver_v2::generateFlowBoundsConstraints() {
	EdgeIF* edge { };
	VertexIdx sourceVertexIdx { };
	VertexIdx targetVertexIdx { };
	EdgeCount flowUpperBound { numberOfVertices - 1 };

	INFO_NOARG(logger,
			LogBundleKey::CPLPIMST2_BUILD_MODEL_FLOW_BOUNDS_CONSTRAINTS);

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

		INFO(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_FLOW_BOUNDS_CONSTRAINT,
				sourceVertexIdx, targetVertexIdx, flowUpperBound,
				sourceVertexIdx, targetVertexIdx,
				getVariableName(
						flowVariablesMap.at(sourceVertexIdx).at(
								targetVertexIdx)).c_str(), flowUpperBound,
				getVariableName(
						edgeVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first).c_str());

		model.add(
				flowVariablesMap.at(sourceVertexIdx).at(targetVertexIdx)
						<= IloNum(flowUpperBound)
								* edgeVariableMap.at(sourceVertexIdx).at(
										targetVertexIdx).first);

		INFO(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_FLOW_BOUNDS_CONSTRAINT,
				targetVertexIdx, sourceVertexIdx, flowUpperBound,
				sourceVertexIdx, targetVertexIdx,
				getVariableName(
						flowVariablesMap.at(targetVertexIdx).at(
								sourceVertexIdx)).c_str(), flowUpperBound,
				getVariableName(
						edgeVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first).c_str());

		model.add(
				flowVariablesMap.at(targetVertexIdx).at(sourceVertexIdx)
						<= IloNum(flowUpperBound)
								* edgeVariableMap.at(sourceVertexIdx).at(
										targetVertexIdx).first);

	}
}
Пример #3
0
IloExpr minBeamletStr(IloEnv & env, IloNumVarArray & w, Sparse_Matrix<IloInt> & vox)
{
	IloExpr obj(env);

	for(int i=0;i<w.getSize();++i)
	{
		obj += w[i]/IloNum(100);
	}

	return obj;
}
Пример #4
0
IloExpr minDoses(IloEnv & env, IloNumVarArray & w, Sparse_Matrix<IloInt>& vox)
{
	IloExpr obj(env);

	for(int i=0;i<vox.a.size();++i)
	{
		obj += vox.a[i]*w[vox.ja[i]];
	}

	obj /= IloNum(vox.m);

	return obj;
}
Пример #5
0
IloNum DistHelper::intTo(IloNum T)
{
    IloNum sum=0.;
    for(unsigned int i=0; i<Region->size(); ++i)
    {
        if( T - D((*Region)[i], *vox, *w)> 0) {
            sum += T - D((*Region)[i], *vox, *w);
        }
    }


    return sum/IloNum(Region->size());
}
Пример #6
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
Пример #7
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()
Пример #8
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
int main(int argc, const char* argv[]){
  IloEnv env;
  try {
    const char* filename = "../../../examples/data/learningeffect_default.data";
    IloInt failLimit = IloIntMax;
    if (argc > 1)
      filename = argv[1];
    if (argc > 2)
      failLimit = atoi(argv[2]);
    std::ifstream file(filename);
    if (!file){
      env.out() << "usage: " << argv[0] << " <file> <failLimit>" << std::endl;
      throw FileError();
    }

    IloModel model(env);
    IloInt nbJobs, nbMachines;
    file >> nbJobs;
    file >> nbMachines;
    IloIntervalVarArray2 machines(env, nbMachines);
    IloIntArray2 sizes(env, nbMachines);
    for (IloInt j = 0; j < nbMachines; j++) {
      machines[j] = IloIntervalVarArray(env);
      sizes[j] = IloIntArray(env);
    }
    IloIntExprArray ends(env);
    for (IloInt i = 0; i < nbJobs; i++) {
      IloIntervalVar prec;
      for (IloInt j = 0; j < nbMachines; j++) {
        IloInt m, d;
        file >> m;
        file >> d;
        IloIntervalVar ti(env);
        machines[m].add(ti);
        sizes[m].add(d);
        if (0 != prec.getImpl())
          model.add(IloEndBeforeStart(env, prec, ti));
        prec = ti;
      }
      ends.add(IloEndOf(prec));
    }
    for (IloInt j = 0; j < nbMachines; j++) {
      IloInt lef;
      file >> lef;
      IloNum alpha = lef/100.0;
      IloIntervalVarArray chain(env);
      IloIntVarArray indices(env);
      IloIntervalVar prec;
      for(IloInt i = 0; i < nbJobs; ++i) {
        IloIntervalVar ti = machines[j][i];
        IloInt d = sizes[j][i];
        ti.setSizeMax(d);
        // Building of the chain of intervals for the machine.
        IloIntervalVar syncti(env);
        if (prec.getImpl()) 
          model.add(IloEndBeforeStart(env, prec, syncti));
        prec = syncti;
        IloIntVar index(env, 0, nbJobs - 1);
        // Learning effect captured by the decreasing function
        // of the position (0 <= alpha <= 1).
        // At first position in the sequence index = 0; there is no
        // learning effect and duration of the task is its nominal duration
        model.add(IloSizeOf(ti) == IloFloor(IloNum(d)*IloPower(alpha, index)));
        chain.add(syncti);
        indices.add(index);
      }
      model.add(IloIsomorphism(env, chain, machines[j], indices, nbJobs));

      // The no-overlap is a redundant constraint in this quite simple
      // model - it is used only to provide stronger inference.
      model.add(IloNoOverlap(env, machines[j]));
    }
    IloObjective objective = IloMinimize(env,IloMax(ends));
    model.add(objective);
    
    IloCP cp(model);
    cp.setParameter(IloCP::FailLimit, failLimit);
    cp.setParameter(IloCP::LogPeriod, 10000);
    cp.out() << "Instance \t: " << filename << std::endl;
    if (cp.solve()) {
      cp.out() << "Makespan \t: " << cp.getObjValue() << std::endl;
    } else {
      cp.out() << "No solution found."  << std::endl;
    }
  } catch(IloException& e){
    env.out() << " ERROR: " << e << std::endl;
  }
  env.end();
  return 0;
}
Пример #10
0
void CPLEX_LP_IMSTSolver_v2::generateIncrementalConstraint(IncrementalParam k) {
	model.add(
			IloSum(edgeAddVariableArray) + IloSum(edgeDropVariableArray)
					<= 2 * IloNum(k));
}