Exemple #1
0
int
main (void) {
   IloEnv env;
   try {
      IloModel model(env);

      IloNumVarArray var(env);
      IloRangeArray con(env);
      populatebyrow (model, var, con);

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

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

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

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

   env.end();
   return 0;

}  // END main
Exemple #2
0
ILOSTLBEGIN

//typedef IloArray<IloNumArray> TwoDMatrix;

int main(int argc, char **argv) 
{
	IloEnv env;
	try 
	{
		IloNumVar X(env, 0, IloInfinity, ILOFLOAT);
		IloNum X_val;
		IloNumVar Y(env, 0, 10, ILOINT);
		IloNum Y_val;
		IloModel model(env);
		IloExpr Obj(env);
		Obj = 5*X - 3*Y;
		model.add(IloMinimize(env,Obj)); // IloMinimize is used for minimization problems
		//Alternatively, model.add(IloMinimize(env,Obj)); can be replaced by the following three lines.
		//This is useful while iterating in Decomposition Techniques where the objective function is redefined at each iteration
		//IloObjective Objective = IloMinimize(env); 
		//model.add(Objective); 
		//Objective.setExpr(Obj);

		Obj.end();
		model.add(X + 2*Y >= 10);
		model.add(2*X - Y >= 0);
		model.add(X - 3*Y >= -13);
		// Optimize
		IloCplex cplex(model);
		//cplex.setOut(env.getNullStream()); // This is to supress the output of Branch & Bound Tree on screen
		//cplex.setWarning(env.getNullStream()); //This is to supress warning messages on screen
		cplex.solve();//solving the MODEL
		if (cplex.getStatus() == IloAlgorithm::Infeasible) // if the problem is infeasible
		{
			env.out() << "Problem Infeasible" << endl; 
		}
		X_val = cplex.getValue(X);
		Y_val = cplex.getValue(Y);
		// Print results
		cout<< "Objective Value = " << cplex.getObjValue() << endl;
		cout<<"X = "<<X_val<<endl;
		cout<<"Y = "<<Y_val<<endl;
	}
	catch(IloException &e) 
	{
		env.out() << "ERROR: " << e << endl;
	}
	catch(...)
	{
		env.out() << "Unknown exception" << endl;
	}
	env.end();
	return 0;
}
Exemple #3
0
int
main (int argc, char **argv)
{
   char const *vmconfig = NULL;

   // Check command line length (exactly two arguments are required).
   if ( argc != 3 ) {
      usage (argv[0]);
      return -1;
   }

   // Pick up VMC from command line.
   vmconfig = argv[1];

   // Solve the model.
   int exitcode = 0;
   IloEnv env;
   try {
      // Create and read the model.
      IloModel model(env);
      IloCplex cplex(model);
      cplex.importModel(model, argv[2]);

      // Load the virtual machine configuration.
      // This will force solve() to use parallel distributed MIP.
      cplex.readVMConfig(vmconfig);

      // Solve the problem and display some results.
      if ( cplex.solve() )
         env.out() << "Solution value  = " << cplex.getObjValue() << endl;
      else
         env.out() << "No solution" << endl;
      env.out() << "Solution status = " << cplex.getStatus() << endl;

      // Cleanup.
      cplex.end();
      model.end();
   }
   catch (IloException& e) {
      cerr << "Concert exception caught: " << e << endl;
      exitcode = -1;
   }
   catch (...) {
      cerr << "Unknown exception caught" << endl;
      exitcode = -1;
   }

   env.end();

   return exitcode;

}  // END main
Exemple #4
0
int
main (int argc, char **argv)
{
   IloEnv   env;
   try {
      IloModel model(env, "example");

      IloNumVarArray var(env);
      IloRangeArray  rng(env);
      populatebycolumn (model, var, rng);

      IloCplex cplex(model);

      IloCplex::BasisStatusArray cstat(env), rstat(env);
      cstat.add(IloCplex::AtUpper);
      cstat.add(IloCplex::Basic);
      cstat.add(IloCplex::Basic);
      rstat.add(IloCplex::AtLower);
      rstat.add(IloCplex::AtLower);
      cplex.setBasisStatuses(cstat, var, rstat, rng);
      cplex.solve();

      cplex.out() << "Solution status = " << cplex.getStatus() << endl;
      cplex.out() << "Solution value  = " << cplex.getObjValue() << endl;
      cplex.out() << "Iteration count = " << cplex.getNiterations() << endl;

      IloNumArray vals(env);
      cplex.getValues(vals, var);
      env.out() << "Values        = " << vals << endl;
      cplex.getSlacks(vals, rng);
      env.out() << "Slacks        = " << vals << endl;
      cplex.getDuals(vals, rng);
      env.out() << "Duals         = " << vals << endl;
      cplex.getReducedCosts(vals, var);
      env.out() << "Reduced Costs = " << vals << endl;

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

   env.end();
   return 0;
}  // END main
Exemple #5
0
int main(int , const char * []){
  IloEnv env;
  try {
    IloModel model(env);
    IloIntVar Belgium(env, 0, 3), Denmark(env, 0, 3),
      France(env, 0, 3), Germany(env, 0, 3),
      Luxembourg(env, 0, 3), Netherlands(env, 0, 3);
    model.add(Belgium != France);
    model.add(Belgium != Germany);
    model.add(Belgium != Netherlands);
    model.add(Belgium != Luxembourg);
    model.add(Denmark == Germany);
    model.add(France != Germany);
    model.add(France != Luxembourg);
    model.add(Germany != Luxembourg);
    model.add(Germany != Netherlands);
    IloCP cp(model);
    cp.setParameter(IloCP::LogVerbosity, IloCP::Quiet);
    if (cp.solve()){
      cp.out() << std::endl << cp.getStatus() << " Solution" << std::endl;
      cp.out() << "Belgium:     " << Names[cp.getValue(Belgium)] << std::endl;
      cp.out() << "Denmark:     " << Names[cp.getValue(Denmark)] << std::endl;
      cp.out() << "France:      " << Names[cp.getValue(France)] << std::endl;
      cp.out() << "Germany:     " << Names[cp.getValue(Germany)] << std::endl;
      cp.out() << "Luxembourg:  " << Names[cp.getValue(Luxembourg)]  << std::endl;
      cp.out() << "Netherlands: " << Names[cp.getValue(Netherlands)] << std::endl;
    }
  }
  catch (IloException& ex) {
    env.out() << "Error: " << ex << std::endl;
  }
  env.end();
  return 0;
}
Exemple #6
0
int
main (int argc, char **argv)
{
   IloEnv env;
   try {
      IloModel model(env);
      IloCplex cplex(env);

      if ( argc != 2 ) {
         usage (argv[0]);
         throw(-1);
      }

      IloObjective   obj;
      IloNumVarArray var(env);
      IloRangeArray  rng(env);
      IloSOS1Array   sos1(env);
      IloSOS2Array   sos2(env);
      IloRangeArray  lazy(env);
      IloRangeArray  cuts(env);

      cplex.importModel(model, argv[1], obj, var, rng, sos1, sos2, lazy, cuts);

      cplex.extract(model);

      if ( lazy.getSize() > 0 )  cplex.addLazyConstraints (lazy);
      if ( cuts.getSize() > 0 )  cplex.addUserCuts (cuts);

      cplex.solve();

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

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

   env.end();
   return 0;
}  // END main
int main(int, const char * []) {
  IloEnv env;
  try {
    IloIntVarArray x(env);
    for (IloInt i = 0; i < 10; i++) {
      char name[6];
      sprintf(name, "X%ld", i);
      x.add(IloIntVar(env, 0, 100 - 2*(i / 2), name));
    }
    IloModel mdl(env);
    mdl.add(IloAllDiff(env, x));
    mdl.add(x);

    IloIntVarChooser varChooser   = ChooseSmallestCentroid(env);
    IloIntValueChooser valChooser = ChooseSmallestDistanceFromCentroid(env);
    IloSearchPhase sp1(env, x, varChooser, valChooser);

    IloIntVarEval   varEval       = Centroid(env);
    IloIntValueEval valEval       = DistanceFromCentroid(env);
    IloSearchPhase sp2(env, x, IloSelectSmallest(varEval),
                               IloSelectSmallest(valEval));

    // sp2 can have ties as two variable or values could evaluate
    // to the same values.  sp3 shows how to break these ties
    // choosing, for equivalent centroid and distance-to-centroid
    // evaluations, the lowest indexed variable in x and the
    // lowest value.
    IloVarSelectorArray selVar(env);
    selVar.add(IloSelectSmallest(varEval));
    selVar.add(IloSelectSmallest(IloVarIndex(env, x))); // break ties on index

    IloValueSelectorArray selValue(env);
    selValue.add(IloSelectSmallest(valEval));
    selValue.add(IloSelectSmallest(IloValue(env))); // break ties on smallest

    IloSearchPhase sp3(env, x, selVar, selValue);

    IloCP cp(mdl);
    cp.setParameter(IloCP::Workers, 1);
    cp.setParameter(IloCP::SearchType, IloCP::DepthFirst);
    cp.setParameter(IloCP::LogPeriod, 1);
    cp.out() << "Choosers" << std::endl;
    cp.solve(sp1);
    cp.out() << cp.domain(x) << std::endl;

    cp.out() << "Evaluators" << std::endl;
    cp.solve(sp2);
    cp.out() << cp.domain(x) << std::endl;
    cp.out() << "Evaluators (with tie-break)" << std::endl;
    cp.solve(sp3);
    cp.out() << cp.domain(x) << std::endl;

    cp.end();
  } catch (IloException & ex) {
    env.out() << "Caught: " << ex << std::endl;
  }
  env.end();
  return 0;
}
int
main (int argc, char **argv)
{
   IloEnv   env;
   try {
      IloModel model(env);
      IloCplex cplex(env);

      if ( argc != 2 ) {
         usage (argv[0]);
         throw(-1);
      }

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

      cplex.use(Rounddown(env, var));

      cplex.extract(model);
      // Check model is all binary except for objective constant variable
      if ( cplex.getNbinVars() < cplex.getNcols() - 1 ) {
         cerr << "Problem contains non-binary variables, exiting." << endl;
         throw (-1);
      }
      cplex.setParam(IloCplex::Param::MIP::Strategy::Search,
                     IloCplex::Traditional);
      cplex.solve();

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

   env.end();
   return 0;
}  // END main
int
main(int argc, char** argv)
{
   IloEnv env;
   try {
      IloModel m(env);
      IloCplex cplex(env);
      IloObjective   obj;
      IloNumVarArray vars(env);
      IloRangeArray  rngs(env);

      const char* datadir = (argc >= 2) ? argv[1] : "../../../examples/data";
      char *fname = new char[strlen(datadir) + 1 + strlen("noswot.mps") + 1];
      sprintf(fname, "%s/noswot.mps", datadir);
      env.out() << "reading " << fname << endl;
      cplex.importModel(m, fname, obj, vars, rngs);
      delete[] fname;

      env.out() << "extracting model ..." << endl;
      cplex.extract(m);
      IloRangeArray cuts(env);
      makeCuts(cuts, vars);

      // Use addUserCuts when the added constraints strengthen the
      // formulation.  Use addLazyConstraints when the added constraints
      // remove part of the feasible region.  Use addCuts when you are
      // not certain.

      cplex.addUserCuts(cuts);
      cuts.endElements();
      cuts.end();

      cplex.setParam(IloCplex::Param::MIP::Interval, 1000);
      env.out() << "solving model ...\n";

      cplex.solve();
      env.out() << "solution status is " << cplex.getStatus() << endl;
      env.out() << "solution value  is " << cplex.getObjValue() << endl;
   }
   catch (IloException& ex) {
      cerr << "Error: " << ex << endl;
   }
   env.end();
   return 0;
}
Exemple #10
0
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
int
main(int argc, char** argv)
{
   IloEnv env;
   try {
      IloModel m(env);
      IloCplex cplex(env);
    
      IloObjective   obj;
      IloNumVarArray var(env);
      IloRangeArray  con(env);

      const char* datadir = (argc >= 2) ? argv[1] : "../../../examples/data";
      char *fname = new char[strlen(datadir) + 1 + strlen("noswot.mps") + 1];
      sprintf(fname, "%s/noswot.mps", datadir);
      env.out() << "reading " << fname << endl;
      cplex.importModel(m, fname, obj, var, con);
      delete[] fname;
    
      env.out() << "constructing cut callback ..." << endl;
      
      IloExprArray lhs(env);
      IloNumArray  rhs(env);
      makeCuts(var, lhs, rhs);
      cplex.use(CtCallback(env, lhs, rhs, cplex.getParam(
         IloCplex::Param::Simplex::Tolerances::Feasibility)));
    
      env.out() << "extracting model ..." << endl;
      cplex.extract(m);
    
      cplex.setParam(IloCplex::Param::MIP::Interval, 1000);
      cplex.setParam(IloCplex::Param::MIP::Strategy::Search,
                     IloCplex::Traditional);
      env.out() << "solving model ...\n";
      cplex.solve();
      env.out() << "solution status is " << cplex.getStatus() << endl;
      env.out() << "solution value  is " << cplex.getObjValue() << endl;
   }
   catch (IloException& ex) {
      cerr << "Error: " << ex << endl;
   }
   env.end();
   return 0;
}
int main(int argc, const char* argv[]){
  IloEnv env;
  try {
    const char* filename = "../../../examples/data/sched_conflict.data";
    IloInt failLimit = 10000;
    if (argc > 1)
      filename = argv[1];
    if (argc > 2)
      failLimit = atoi(argv[2]);
    IloConstraintArray allCts(env);
    IloConstraintArray capacityCts(env);
    IloConstraintArray precedenceCts(env);
    IloModel model = ReadModel(env, filename, capacityCts, precedenceCts);
    allCts.add(capacityCts);
    allCts.add(precedenceCts);
    IloCP cp(model);
    cp.setParameter(IloCP::FailLimit, failLimit);
    cp.setParameter(IloCP::CumulFunctionInferenceLevel, IloCP::Extended);
    cp.setParameter(IloCP::ConflictRefinerOnVariables, IloCP::On);
    cp.out() << "Instance \t: " << filename << std::endl;
    if (cp.solve()) {
      // A solution was found
      cp.out() << "Solution found with makespan : " << cp.getObjValue() << std::endl;
    } else {
      IloInt status = cp.getInfo(IloCP::FailStatus);
      if (status != IloCP::SearchHasFailedNormally) {
        // No solution found but problem was not proved infeasible
        cp.out() << "No solution found but problem was not proved infeasible." << std::endl;
      } else {
        // Run conflict refiner only if problem was proved infeasible
        cp.out() << "Infeasible problem, running conflict refiner ..." << std::endl;
        cp.out() << std::endl;
        cp.out() << "SCENARIO 1: Basic conflict refiner:" << std::endl;
        cp.out() << std::endl;
        runBasicConflictRefiner(cp);
        cp.setParameter(IloCP::LogVerbosity, IloCP::Quiet);
        cp.out() << "SCENARIO 2: Conflict refiner with preference on resource capacity constraints:" << std::endl;
        cp.out() << std::endl;
        runConflictRefinerWithPreferences(cp, capacityCts, precedenceCts);
        cp.out() << "SCENARIO 3: Conflict refiner with preference on precedence constraints:" << std::endl;
        cp.out() << std::endl;
        runConflictRefinerWithPreferences(cp, precedenceCts, capacityCts);
        cp.out() << "SCENARIO 4: Conflict partition:" << std::endl; 
        cp.out() << std::endl;
        runConflictRefinerPartition(cp, allCts);
        cp.out() << "SCENARIO 5: All conflicts:" << std::endl;
        cp.out() << std::endl;
        runConflictRefinerAllConflicts(cp, allCts);
      }
    }
  } catch (IloException& ex) {
    env.out() << "Caught: " << ex << std::endl;
  }
  env.end();
  return 0;
}
Exemple #13
0
int
main (void) {
   IloEnv env;
   try {
      IloModel model(env);

      IloNumVarArray var(env);
      IloRangeArray con(env);
      populatebyrow (model, var, con);

      IloCplex cplex(model);
      IloNumVarArray ordvar(env, 2);
      IloNumArray    ordpri(env, 2);
      ordvar[0] = var[1]; ordvar[1] = var[3];
      ordpri[0] = 8.0;    ordpri[1] = 7.0;
      cplex.setPriorities (ordvar, ordpri);
      cplex.setDirection(var[1], IloCplex::BranchUp);
      cplex.setDirection(var[3], IloCplex::BranchDown);
      cplex.solve();

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

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

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

   env.end();
   return 0;

}  // END main
int
main (int argc, char **argv)
{
    IloEnv   env;
    try {
        IloModel model(env);
        IloCplex cplex(env);

        if ( argc != 2 ) {
            usage (argv[0]);
            throw(-1);
        }

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

        cplex.use(SOSbranch(env, sos1));
        cplex.setParam(IloCplex::Param::MIP::Strategy::Search,
                       IloCplex::Traditional);

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

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

    env.end();
    return 0;
}  // END main
Exemple #15
0
int
main (int argc, char **argv)
{
   IloEnv env;
   try {
      IloModel model(env, "example");

      IloNumVarArray var(env);
      IloRangeArray  rng(env);
      populatebycolumn (model, var, rng);

      IloCplex cplex(model);
      cplex.setOut(env.getNullStream());
      cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Primal);
      cplex.use(MyCallback(env));
      cplex.solve();

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

      IloNumArray vals(env);
      cplex.getValues(vals, var);
      env.out() << "Values        = " << vals << endl;
      cplex.getSlacks(vals, rng);
      env.out() << "Slacks        = " << vals << endl;
      cplex.getDuals(vals, rng);
      env.out() << "Duals         = " << vals << endl;
      cplex.getReducedCosts(vals, var);
      env.out() << "Reduced Costs = " << vals << endl;

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

   env.end();
   return 0;
}  // END main
int main (void) {
  IloEnv env;
  try {

      IloModel model(env); // declaration du nodel
      IloNumVarArray var(env); // liste des variables de decision
      IloRangeArray con(env); // liste des contraintes a ajouter a notre probleme
      IloNumVarArray duals(env);

      populatebyrow (model, var, con); // remplir les variables avec les valeurs adequat
      IloCplex cplex(model);
      cplex.solve();

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


      model.add(var[0] == 0);
      cplex.solve();
      cplex.getValues(vals, var);
      env.out() << "Solution status = " << cplex.getStatus() << endl;
      env.out() << "Solution value  = " << cplex.getObjValue() << endl;
      env.out() << "Values = " << vals << endl;

      //cplex.exportModel("pl.lp");
    }
    catch (IloException& e) {
      cerr << "Concert exception caught: " << e << endl;
    }
    catch (...) {
      cerr << "Unknown exception caught" << endl;
    }
  env.end();
  return 0;
}
int main(int, const char * []) {
    IloEnv env;
    try {
        IloInt i,j;
        IloModel model(env);

        IloNumExpr cost(env);
        IloIntervalVarArray allTasks(env);
        IloIntervalVarArray joeTasks(env);
        IloIntervalVarArray jimTasks(env);
        IloIntArray joeLocations(env);
        IloIntArray jimLocations(env);

        MakeHouse(model, cost, allTasks, joeTasks, jimTasks, joeLocations,
                  jimLocations, 0, 0,   120, 100.0);
        MakeHouse(model, cost, allTasks, joeTasks, jimTasks, joeLocations,
                  jimLocations, 1, 0,   212, 100.0);
        MakeHouse(model, cost, allTasks, joeTasks, jimTasks, joeLocations,
                  jimLocations, 2, 151, 304, 100.0);
        MakeHouse(model, cost, allTasks, joeTasks, jimTasks, joeLocations,
                  jimLocations, 3, 59,  181, 200.0);
        MakeHouse(model, cost, allTasks, joeTasks, jimTasks, joeLocations,
                  jimLocations, 4, 243, 425, 100.0);

        IloTransitionDistance tt(env, 5);
        for (i=0; i<5; ++i)
            for (j=0; j<5; ++j)
                tt.setValue(i, j, IloAbs(i-j));

        IloIntervalSequenceVar joe(env, joeTasks, joeLocations, "Joe");
        IloIntervalSequenceVar jim(env, jimTasks, jimLocations, "Jim");

        model.add(IloNoOverlap(env, joe, tt));
        model.add(IloNoOverlap(env, jim, tt));

        model.add(IloMinimize(env, cost));

        /* EXTRACTING THE MODEL AND SOLVING. */
        IloCP cp(model);
        if (cp.solve()) {
            cp.out() << "Solution with objective " << cp.getObjValue() << ":" << std::endl;
            for (i=0; i<allTasks.getSize(); ++i) {
                cp.out() << cp.domain(allTasks[i]) << std::endl;
            }
        } else {
            cp.out() << "No solution found. " << std::endl;
        }
    } catch (IloException& ex) {
        env.out() << "Error: " << ex << std::endl;
    }
    env.end();
    return 0;
}
Exemple #18
0
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;
}
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
Exemple #20
0
int main(int argc, const char *argv[]){
  IloEnv env;
  try {
    IloModel model(env);
    IloInt nbTransmitters = GetTransmitterIndex(nbCell, 0);
    IloIntVarArray freq(env, nbTransmitters, 0, nbAvailFreq - 1);
    freq.setNames("freq");
    for (IloInt cell = 0; cell < nbCell; cell++)
      for (IloInt channel1 = 0; channel1 < nbChannel[cell]; channel1++)
        for (IloInt channel2= channel1+1; channel2 < nbChannel[cell]; channel2++)
          model.add(IloAbs(  freq[GetTransmitterIndex(cell, channel1)]
                             - freq[GetTransmitterIndex(cell, channel2)] )
                    >= 16);
    for (IloInt cell1 = 0; cell1 < nbCell; cell1++)
      for (IloInt cell2 = cell1+1; cell2 < nbCell; cell2++)
        if (dist[cell1][cell2] > 0)
          for (IloInt channel1 = 0; channel1 < nbChannel[cell1]; channel1++)
            for (IloInt channel2 = 0; channel2 < nbChannel[cell2]; channel2++)
              model.add(IloAbs(  freq[GetTransmitterIndex(cell1, channel1)]
                                 - freq[GetTransmitterIndex(cell2, channel2)] )
                        >= dist[cell1][cell2]);
    
    // Minimizing the total number of frequencies
    IloIntExpr nbFreq = IloCountDifferent(freq); 
    model.add(IloMinimize(env, nbFreq));
    
    IloCP cp(model);
    cp.setParameter(IloCP::CountDifferentInferenceLevel, IloCP::Extended);
    cp.setParameter(IloCP::FailLimit, 40000);
    cp.setParameter(IloCP::LogPeriod, 100000);

    if (cp.solve()) {
      for (IloInt cell = 0; cell < nbCell; cell++) {
        for (IloInt channel = 0; channel < nbChannel[cell]; channel++)
          cp.out() << cp.getValue(freq[GetTransmitterIndex(cell, channel)])
                   << "  " ;
        cp.out() << std::endl;
      }
      cp.out() << "Total # of sites       " << nbTransmitters << std::endl;
      cp.out() << "Total # of frequencies " << cp.getValue(nbFreq) << std::endl;
    } else
      cp.out() << "No solution found."  << std::endl;
    cp.end();
  } catch (IloException & ex) {
    env.out() << "Caught: " << ex << std::endl;
  }
  env.end();
  return 0;
}
int main(int argc, const char * argv[]) {
  IloEnv env;
  try {
    IloModel model(env);

    IloInt n = 10;
    if (argc > 1)
      n = atoi(argv[1]);
    if ((n % 2) == 1)
      n++;
    env.out() << "Finding schedule for " << n << " teams" << std::endl;

    //Calculate the data
    //Declare the game, home team and away team variables
    //Calculate the allowed tuples
    //Add the constraint on allowed combinations

    //Add the alldiff constraint
    //Add the inverse constraint
    //Add the week of game constraint

    //Create the different halves constraint
    //Create the distance constraint
    //Add max break length constraints
    //Add the constraint on first and last weeks

    //Add the objective

    //Add surrogate constraints
    //Add more surrogate constraints
    //Add constraints to fix first week
    //Add the slot order constraint

    //Create an instance of IloCP
    //Add the time limit
    //Create the search selectors
    //Create the tuning object
    //Search for a solution

      cp.out() << "Solution at " << cp.getValue(breaks) << std::endl;
    }
    cp.endSearch();
    cp.end();
  } catch (IloException & ex) {
Exemple #22
0
int CProblem::setModel()
{
	//time_t start, end;

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

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

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

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

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

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

		}

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

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

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

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

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

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

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

	} // end try
	catch (IloException& e)
	{
		std::cerr << "Concert exception caught: " << e << std::endl;
	} catch (...)
	{
		std::cerr << "Unknown exception caught" << std::endl;
	}
	env.end();
	return 0;
}
Exemple #23
0
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
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
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()
int main(int argc, const char* argv[]){
  IloEnv env;
  try {
    const char* filename = "../../../examples/data/flowshop_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();
    }

    IloInt i,j;
    IloModel model(env);
    IloInt nbJobs, nbMachines;
    file >> nbJobs;
    file >> nbMachines;
    IloIntervalVarArray2 machines(env, nbMachines);
    for (j = 0; j < nbMachines; j++)
      machines[j] = IloIntervalVarArray(env);
    IloIntExprArray ends(env);
    for (i = 0; i < nbJobs; i++) {
      IloIntervalVar prec;
      for (j = 0; j < nbMachines; j++) {
        IloInt d;
        file >> d;
        IloIntervalVar ti(env, d);
        machines[j].add(ti);
        if (0 != prec.getImpl())
          model.add(IloEndBeforeStart(env, prec, ti));
        prec = ti;
      }
      ends.add(IloEndOf(prec));
    }

    IloIntervalSequenceVarArray seqs(env,nbMachines);
    for (j = 0; j < nbMachines; j++) {
      seqs[j] = IloIntervalSequenceVar(env, machines[j]);
      model.add(IloNoOverlap(env,seqs[j]));
      if (0<j) {
        model.add(IloSameSequence(env, seqs[0],seqs[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;
}
Exemple #27
0
// 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;   
}
Exemple #28
0
int
main(int argc)
{


	IloEnv   env;
	try {
		IloModel model(env);

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

		populatebynonzero(model, varOutput, varHelp, cons);

		IloCplex cplex(model);

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

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

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


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

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

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

	env.end();
	cin.get();
	return 0;
}  // END main
Exemple #29
0
int CProblem::setModel() {
	//time_t start, end;

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

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

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

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

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

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

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

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

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

				}
			}
*/

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

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



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

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

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

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

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

		std::cout << "STATUS : "<< cplex.getStatus() << "\n";
		/* get the solution*/
		env.out() << "Solution status = " << cplex.getStatus() << "\n";
		numconst = cplex.getNrows();
		env.out() << " Number of constraints = " << numconst << "\n";
		lambda_G_d=cplex.getObjValue();
		env.out() << "Solution value  = " << lambda_G_d << "\n";
		for (unsigned int u=0; u<n; u++) {
			C.push_back(cplex.getValue(c[u]));
			std::cout << "c(" << u << ")=" << C[u]<< " ";
		}
		std::cout <<"\n";
		/*
		for (unsigned int u=0; u<n; u++) {
			for (unsigned int v=0; v<u; v++) {
				std::cout<< "z[" << u <<"][" << v << "]="<< cplex.getValue( z[u][v]) << " ";
				Z.push_back(cplex.getValue( z[u][v]));
			}
			std::cout << "\n";
		}
		std::cout <<"\n";
		 */
	}	// end try
	catch (IloException& e) {
		std::cerr << "Concert exception caught: " << e << std::endl;
	}
	catch (...) {
		std::cerr << "Unknown exception caught" << std::endl;
	}
	env.end();
	return 0;
}
Exemple #30
0
int
main (int argc, char **argv)
{
   char const *vmconfig = NULL;

   // Check command line length (exactly two arguments are required).
   if ( argc != 3 ) {
      usage (argv[0]);
      return -1;
   }

   // Pick up VMC from command line.
   vmconfig = argv[1];

   // Solve the model.
   int exitcode = 0;
   IloEnv env;
   try {
      // Create and read the model.
      IloModel model(env);
      IloCplex cplex(model);

      IloObjective   obj;
      IloNumVarArray var(env);
      IloRangeArray  rng(env);
      IloSOS1Array   sos1(env);
      IloSOS2Array   sos2(env);
      IloRangeArray  lazy(env);
      IloRangeArray  cuts(env);

      cplex.importModel(model, argv[2], obj, var, rng, sos1, sos2,
                        lazy, cuts);

      cplex.extract(model);

      if ( lazy.getSize() > 0 )  cplex.addLazyConstraints (lazy);
      if ( cuts.getSize() > 0 )  cplex.addUserCuts (cuts);

      // Load the virtual machine configuration.
      // This will force solve() to use parallel distributed MIP.
      cplex.readVMConfig(vmconfig);

      // Install logging info callback.
      IloNum lastObjVal = (obj.getSense() == IloObjective::Minimize ) ?
         IloInfinity : -IloInfinity;
      cplex.use(loggingCallback(env, var, -100000, lastObjVal,
                                cplex.getCplexTime(), cplex.getDetTime()));
      // Turn off CPLEX logging
      cplex.setParam(IloCplex::Param::MIP::Display, 0);


      // Solve the problem and display some results.
      if ( cplex.solve() )
         env.out() << "Solution value  = " << cplex.getObjValue() << endl;
      else
         env.out() << "No solution" << endl;
      env.out() << "Solution status = " << cplex.getStatus() << endl;

      // Cleanup.
      cplex.end();
      model.end();
   }
   catch (IloException& e) {
      cerr << "Concert exception caught: " << e << endl;
      exitcode = -1;
   }
   catch (...) {
      cerr << "Unknown exception caught" << endl;
      exitcode = -1;
   }

   env.end();

   return exitcode;

}  // END main