コード例 #1
0
ファイル: ilomipex1.cpp プロジェクト: andreasmattas/testcode
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
コード例 #2
0
ファイル: ilolpex3.cpp プロジェクト: annaPolytech/PRD
ILOSTLBEGIN

int
main()
{
   IloEnv   env;
   try {
      IloModel model(env, "chvatal");

      IloNumVarArray x(env, 12, 0.0, 50.0);
      model.add(IloMinimize(env, x[0] + x[1] + x[2] + x[3] + x[4] +
                                 x[5] + x[6] + 2*x[10] + 2*x[11] ));

      model.add(                                   -x[7]-x[8]-x[9]          
         == -1);
      model.add( x[0]                    +x[5]     +x[7]
         ==  4);
      model.add(      x[1]     +x[3]          +x[6]     +x[8]                 
         ==  1);
      model.add(           x[2]     +x[4]                    +x[9]            
         ==  1);
      model.add(                         -x[5]-x[6]               -x[10]+x[11]
         == -2);
      model.add(               -x[3]-x[4]                         +x[10]      
         == -2);
      model.add(-x[0]-x[1]-x[2]                                         -x[11]
         == -1);

      IloCplex cplex(model);
      cplex.setParam(IloCplex::Param::Simplex::Display, 2);
      cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Network);
      cplex.solve();
      cplex.out() << "After network optimization, objective is "
                  << cplex.getObjValue() << endl;

      model.add(2*x[10] + 5*x[11] == 2);
      model.add(  x[0] + x[2] + x[5] == 3);

      cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Dual);
      cplex.solve();

      IloNumArray vals(env);
      cplex.getValues(vals, x);
      cplex.out() << "Solution status " << cplex.getStatus() << endl;
      cplex.out() << "Objective value " << cplex.getObjValue() << endl;
      cplex.out() << "Solution is: " << vals << endl;

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

   env.end();
   return 0;
} // END main
コード例 #3
0
ファイル: instance.cpp プロジェクト: shidanxu/solver
 void Instance::ComputeCPLEXRevenue() {
     IloEnv env;
     IloInt i, j;
     IloModel model(env);
     IloInt nbImpressions = num_impressions_;
     IloInt nbAdvertisers = num_advertisers_;
     
     NumVarMatrix x(env, nbImpressions);
     
     for(i = 0; i < nbImpressions; i++) {
         x[i] = IloNumVarArray(env, nbAdvertisers, 0.0, 1.0, ILOFLOAT);
     }
     
     // Add impression constraints.
     for(i = 0; i < nbImpressions; i++) {
         model.add(IloSum(x[i]) <= 1.0);
     }
     
     // Add weighted contraint.
     for(j = 0; j < nbAdvertisers; j++) {
         IloExpr curr_adv_constraint(env);
         for (__gnu_cxx::hash_map<int, long double>::iterator iter = bids_matrix_[j].begin();
              iter != bids_matrix_[j].end();
              ++iter) {
             curr_adv_constraint += ((double) iter->second) * ((double) weights_[j]) * x[iter->first][j];
         }
         model.add(curr_adv_constraint <= ((double) budgets_[j]));
     }
     
     IloExpr obj_exp(env);
     for(i = 0; i < nbImpressions; i++) {
         for(j = 0; j < nbAdvertisers; j++) {
             obj_exp += ((double) transpose_bids_matrix_[i][j]) * x[i][j];
         }
     }
     
     model.add(IloMaximize(env, obj_exp));
     obj_exp.end();
     
     IloCplex cplex(env);
     cplex.setOut(env.getNullStream());
     cplex.extract(model);
     
     // Optimize the problem and obtain solution.
     if ( !cplex.solve() ) {
         env.error() << "Failed to optimize LP" << endl;
         throw(-1);
     }
     
     cplex.exportModel("/Users/ciocan/Documents/Google/data/example.lp");
     
     cout << "CPLEX opt is " << cplex.getObjValue() << "\n";
     
     env.end();    
 }
コード例 #4
0
ファイル: ilodistmipex1.cpp プロジェクト: annaPolytech/PRD
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
コード例 #5
0
ファイル: ilosocpex1.cpp プロジェクト: renvieir/ioc
int
main (void)
{
   IloEnv env;
   int retval = -1;

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

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

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

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

      env.end();
   } catch (IloException &e) {
      cerr << "IloException: " << e << endl;
      if (env.getImpl())
         env.end();
      ::abort();
   } catch (string& e) {
      cerr << e << endl;
      if (env.getImpl())
         env.end();
      ::abort();
   }
   return retval;
}
コード例 #6
0
ファイル: ilolpex6.cpp プロジェクト: andreasmattas/testcode
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
コード例 #7
0
int
main()
{
   IloEnv env;
   try {
      IloModel model(env);
    
      setData(env);
      IloNumVarArray  inside(env, nbProds);
      IloNumVarArray outside(env, nbProds);
   
      IloObjective obj = IloAdd(model, IloMinimize(env));
    
      // Must meet demand for each product
    
      for(IloInt p = 0; p < nbProds; p++) {
         IloRange demRange = IloAdd(model,
                                    IloRange (env, demand[p], demand[p]));
         inside[p]  = IloNumVar(obj(insideCost[p])  + demRange(1));
         outside[p] = IloNumVar(obj(outsideCost[p]) + demRange(1));
      }
    
      // Must respect capacity constraint for each resource
    
      for(IloInt r = 0; r < nbResources; r++)
         model.add(IloScalProd(consumption[r], inside) <= capacity[r]);
    
      IloCplex cplex(env);
      cplex.extract(model);
    
      cplex.solve();
    
      if (cplex.getStatus() != IloAlgorithm::Optimal)
         cout << "No optimal solution" << endl;
    
      cout << "Solution status: " << cplex.getStatus() << endl;
      displayResults(cplex, inside, outside);
      cout << "----------------------------------------" << endl;
   }
   catch (IloException& ex) {
      cerr << "Error: " << ex << endl;
   }
   catch (...) {
      cerr << "Error" << endl;
   }
   env.end();
   return 0;
}
コード例 #8
0
int
main (int argc, char **argv)
{
   IloEnv   env;
   try {
      IloModel model(env);
      IloNumVarArray var(env);
      IloRangeArray con(env);
      IloRange add_con(env, 0.0, IloInfinity);

      populatebyrow (model, var, con);

      IloCplex cplex(model);

      // When a non-convex objective function is present, CPLEX will
      // raise an exception unless the parameter
      // IloCplex::Param::OptimalityTarget is set to accept first-order optimal
      // solutions
      cplex.setParam(IloCplex::Param::OptimalityTarget,
                     IloCplex::SolutionFirstOrder);

      // CPLEX may converge to either local optimum 
      solveanddisplay(env, cplex, var, con);

      // Add a constraint that cuts off the solution at (-1, 1)
      add_con.setExpr(var[0]);
      model.add(add_con);
      solveanddisplay(env, cplex, var, con);

      // Change the bounds of the newly added constraint to cut off
      // the solution at (1, 1)
      add_con.setBounds(-IloInfinity, 0.0);
      solveanddisplay(env, cplex, var, con);

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

   env.end();

   return 0;
}  // END main
コード例 #9
0
ファイル: ilomipex2.cpp プロジェクト: renvieir/ioc
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
コード例 #10
0
ファイル: startEndModel.cpp プロジェクト: sims2B/Expe_these
int solveSE(const Problem<double>& P,Solution<double,double> &s,const std::vector<int>& config) {  
  try  {
    IloNum start,time_exec;
    const int n = P.nbTask;
    
    // create cplex model
    IloEnv env;
    IloModel model(env);
    IloNumVarMatrix x(env,n),y(env,n),b(env,n), w(env,n);
    IloNumVarArray t(env, 2*n, 0, P.D, ILOFLOAT);
    createModel(P,env,model,t,x,y,b,w,config);
    IloCplex cplex(model);
    setCplexParam(cplex,env,time_limit);

    start = cplex.getCplexTime();
    IloInt cpt=0;
    cplex.use(getFirstSolInfo(env,cpt,start));
    // solve !
    if (cplex.solve()) {	 
      time_exec=cplex.getCplexTime()-start;
      std::cout << "Final status: \t"<< cplex.getStatus() << " en " 
		<< time_exec << std::endl;
      std:: cout << "Final objective: " << cplex.getObjValue() 
		 <<"\nFinal gap: \t" << cplex.getMIPRelativeGap()
		 << std::endl;   
      modelToSol(P,s,cplex,t,x,y,b);
      env.end();
      return 0;
    }
    else if (cplex.getStatus()==IloAlgorithm::Infeasible){
      time_exec=cplex.getCplexTime()-start;
      std::cout << "status: "<< cplex.getStatus() << " en " 
		<< time_exec << std::endl;
    }
    env.end();
    return 1;
  }
  catch (IloException &e) {
    std::cout << "Iloexception in solve" << e << std::endl;
    e.end();
    return 1;
  } 
  catch (...){
    std::cout << "Error unknown\n";
    return 1;
  }
}
コード例 #11
0
ファイル: startEndModel.cpp プロジェクト: sims2B/Expe_these
int LPsolveSE(const Problem<double>& P,const std::vector<int>& config,int time_limite) {  
  try{
    IloNum start,time_exec;
    const int nbTask = P.nbTask;
    const int E=2*nbTask;
    
    IloEnv env;
    IloModel model(env);
    IloNumVarMatrix x(env,nbTask),y(env,nbTask);
    IloNumVarMatrix b(env,nbTask), w(env,nbTask);
    IloNumVarArray t(env, E, 0, P.D, ILOFLOAT);
    
    // create cplex model
    createModel(P,env,model,t,x,y,b,w,config);
    for (int i=0;i<nbTask;++i){
      for (int e=0;e<E;++e){
	model.add(IloConversion(env,x[i][e],ILOFLOAT));
	model.add(IloConversion(env,y[i][e],ILOFLOAT));
      }
    }
    IloCplex cplex(model);
    setCplexParam(cplex,env,time_limite);
    start= cplex.getCplexTime();
      
    // solve !
    if (cplex.solve()) {	 
      time_exec=cplex.getCplexTime()-start;
      std::cout << "Final status: \t"<< cplex.getStatus() << std::endl;
      std::cout << "Final time: \t"<< time_exec << std::endl;
      std:: cout << "Final objective: " << cplex.getObjValue() <<"\nFinal gap: \t" 
		 << cplex.getMIPRelativeGap()<< std::endl;   
            env.end();
      return 0;
    }
    else if (cplex.getStatus()==IloAlgorithm::Infeasible){
      time_exec=cplex.getCplexTime()-start;
      std::cout << "status: "<< cplex.getStatus() << " en " << time_exec << std::endl;
    }
    env.end();
    return 1;
  }
  catch (IloException &e){
    std::cout << "Iloexception in solve" << e << std::endl;
    e.end();
    return  1;
  }
}
コード例 #12
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
コード例 #13
0
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;
}
コード例 #14
0
ファイル: iloqpex1.cpp プロジェクト: andreasmattas/testcode
int
main (int argc, char **argv)
{
   IloEnv   env;
   try {
      IloModel model(env);
      IloNumVarArray var(env);
      IloRangeArray con(env);

      populatebyrow (model, var, con);

      IloCplex cplex(model);

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

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

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

   env.end();

   return 0;
}  // END main
コード例 #15
0
ファイル: ilogoalex3.cpp プロジェクト: renvieir/ioc
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.extract(model); 
      cplex.setParam(IloCplex::Param::MIP::Strategy::Search,
                     IloCplex::Traditional);
    
      IloCplex::Goal iiSumGoal = IloCplex::Apply(cplex, 
                                                 MyBranchGoal(env, var), 
                                                 IISumEvaluator());
      IloCplex::Goal depthGoal = IloCplex::Apply(cplex,
                                                 iiSumGoal,
                                                 DepthEvaluator());
      cplex.solve(depthGoal);
    
      IloNumArray vals(env);
      cplex.getValues(vals, var);
      cout << "Solution status = " << cplex.getStatus() << endl;
      cout << "Solution value  = " << cplex.getObjValue() << endl;
      cout << "Values          = " << vals << endl;
   }
   catch (IloException& e) {
      cerr << "Concert exception caught: " << e << endl;
   }

   env.end();

   return 0;
}
コード例 #16
0
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;
}
コード例 #17
0
ファイル: ilomipex3.cpp プロジェクト: andreasmattas/testcode
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
コード例 #18
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);
        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
コード例 #19
0
ファイル: ilolpex4.cpp プロジェクト: annaPolytech/PRD
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
コード例 #20
0
bool CPlexSolver::solve() {
	IloCplex cplex(model);
	cplex.setParam(IloCplex::MIPEmphasis, CPX_MIPEMPHASIS_FEASIBILITY);
	
	if (cplex.solve()) {
		IloNumArray vals(env);
		cplex.getValues(vals, vars);
		
		// Populate solutionVectors from vals
		SolutionVector solution(vals.getSize());
		for (int i = 0; i < vals.getSize(); i++) {			// IloNumArray does not have iterators, so we do it the hard way
			solution[i] = vals[i];
		}
		solutionVectors.push_back(solution);
		
		return true;
	} else {
		return false;
	}
}
コード例 #21
0
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;
}
コード例 #22
0
void profit_solve(graph g, vector<int>& allocation, vector<double>& pricing, bool integer) {
  int **columns = (int **)malloc(g->bidders * sizeof(int *));
  for(int i = 0; i < g->bidders; i++)
    columns[i] = (int *)calloc(g->items, sizeof(int));
  IloEnv env;
  try {
    if(getVerbosity() != CplexOutput)
      env.setOut(env.getNullStream());
    IloModel model(env);
    IloNumVarArray x(env);
    IloNumVarArray p(env);
    IloNumVarArray z(env);
    IloCplex cplex(model);
    profit_create_vars(g, model, x, p, z, columns);
    profit_create_objective(g, model, x, z, columns);
    model.add(profit_constraints(g, model, x, p, z, columns));
    config_cplex(cplex); 
    if(!integer) {
      model.add(IloConversion(env, x, ILOFLOAT));
    } else {
      profit_load(g, cplex, model, x, p, z, columns, allocation, pricing);
    }
    clock_start();
    if (!cplex.solve()) {
      failed_print(g);
    } else {
      if(integer)
        solution_print(cplex, env, g);  
      else
        relax_print(cplex, env);
    }
  }
  catch (IloException& e) {
    cerr << "Concert exception caught: " << e << endl;
  }
  catch (...) {
    cerr << "Unknown exception caught" << endl;
  }
}
コード例 #23
0
ファイル: CAP_newOrder.cpp プロジェクト: tikhoncheva/work
int CProblem::setModel() {
	//time_t start, end;

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

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

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

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

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

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

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

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

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

				}
			}
*/

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

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



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

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

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

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

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

		std::cout << "STATUS : "<< cplex.getStatus() << "\n";
		/* get the solution*/
		env.out() << "Solution status = " << cplex.getStatus() << "\n";
		numconst = cplex.getNrows();
		env.out() << " Number of constraints = " << numconst << "\n";
		lambda_G_d=cplex.getObjValue();
		env.out() << "Solution value  = " << lambda_G_d << "\n";
		for (unsigned int u=0; u<n; u++) {
			C.push_back(cplex.getValue(c[u]));
			std::cout << "c(" << u << ")=" << C[u]<< " ";
		}
		std::cout <<"\n";
		/*
		for (unsigned int u=0; u<n; u++) {
			for (unsigned int v=0; v<u; v++) {
				std::cout<< "z[" << u <<"][" << v << "]="<< cplex.getValue( z[u][v]) << " ";
				Z.push_back(cplex.getValue( z[u][v]));
			}
			std::cout << "\n";
		}
		std::cout <<"\n";
		 */
	}	// end try
	catch (IloException& e) {
		std::cerr << "Concert exception caught: " << e << std::endl;
	}
	catch (...) {
		std::cerr << "Unknown exception caught" << std::endl;
	}
	env.end();
	return 0;
}
コード例 #24
0
ファイル: stats.cpp プロジェクト: rionda/truefis
int compute_evc_bound_using_sukp(Dataset &dataset,
		const std::unordered_set<const std::set<int>*> &collection, const
		stats_config &stats_conf, std::pair<int,int> &result) {
	std::ifstream dataset_s(dataset.get_path());
	if(! dataset_s.good()) {
		std::cerr << "ERROR: cannot open dataset file" << std::endl;
		dataset_s.close();
		std::exit(EXIT_FAILURE);
	}
	if (collection.empty()) {
		result.first = 0;
		result.second = 0;
		return 1;
	}
	// The following is called U in the pseudocode
	std::unordered_set<int> items;
	int collection_size = 0;
	for (const std::set<int> *itemset : collection) {
		items.insert(itemset->begin(), itemset->end());
		++collection_size;
	}
	// The following is called L in the pseudocode
	std::map<int, int, bool (*)(int,int)> intersection_sizes_counts(reverse_int_comp);
	// The following is called D_C in the pseudocode
	std::set<std::set<int> > intersections;
	std::string line;
	int size = 0;
	while (std::getline(dataset_s, line)) {
		++size;
		const std::set<int> tau = string2itemset(line);
		std::vector<int> intersection_v(tau.size());
		std::vector<int>::iterator it;
		it = std::set_intersection(
				tau.begin(), tau.end(), items.begin(), items.end(),
				intersection_v.begin());
		if (it != intersection_v.begin() && it - intersection_v.begin() != items.size()) {
			std::set<int> intersection(intersection_v.begin(), it);
			std::pair<std::set<std::set<int> >::iterator, bool> insertion_pair = intersections.insert(intersection);
			if (insertion_pair.second) { // intersection was not already in intersections
				std::map<int, int, bool (*)(int,int)>::iterator intersection_it = intersection_sizes_counts.find(intersection.size());
				if (intersection_it == intersection_sizes_counts.end()) { // we've never seen an intersection of this size
					int prev_value = 0; // We add an element with key equal to the intersection size, and value equal to the value of the element with key immediately larger thn this one, or 0 if there is no such element.
					if (! intersection_sizes_counts.empty()) {
						auto longer_intersection_it = intersection_sizes_counts.lower_bound(intersection.size());
						if (longer_intersection_it != intersection_sizes_counts.begin()) {
							--longer_intersection_it;
							prev_value = longer_intersection_it->second;
						}
					}
					intersection_it = (intersection_sizes_counts.emplace(intersection.size(), prev_value)).first;
				}
				// Exploit the sorted nature (in decreasing order) of the map
				for (; intersection_it != intersection_sizes_counts.end(); ++intersection_it) {
					intersection_sizes_counts[intersection_it->first] += 1;
				}
			}
		}
	}
	dataset_s.close();
	dataset.set_size(size); // Set size in the database object
	// We do not need a counter 'i' like in the pseudocode, we can use an
	// iterator that exploits the sorted nature of the map
	std::map<int, int, bool (*)(int,int)>::iterator it = intersection_sizes_counts.begin();
	IloEnv env;
	IloModel model(env);
	if (get_CPLEX_model(model, env, items, collection, it->first, stats_conf.use_antichain) == -1) {
		std::cerr << "ERROR: something went wrong while building the CPLEX model" << std::endl;
		env.end();
		std::exit(EXIT_FAILURE);
	}
	IloCplex cplex(model);
	// Set parameters, like max runtime and tolerance gaps
	set_CPLEX_params(cplex);
	// Redirect output to null stream
	cplex.setOut(env.getNullStream());
	// Iterate over the possible lengths
	while (true) {
		// The following is q in the pseudocode
		double profit = get_SUKP_profit(cplex);
		if (profit == -1.0) {
			std::cerr << "ERROR: something went wrong while solving the SUKP" << std::endl;
			env.end();
			std::exit(EXIT_FAILURE);
		}
		// This is b in the pseudocode
		int bound =  ((int) floor(log2(profit))) + 1;
		if (bound <= it->second) {
			result.first = bound;
			result.second = -1;
			env.end();
			return 1;
		} else {
			++it;
			if (it != intersection_sizes_counts.end()) {
				if (it->first == 1) {
					result.first = 1;
					result.second = -1;
					env.end();
					return 1;
				}
				set_capacity(model, it->first);
			} else {
				env.end();
				break;
			}
		}
	}
	--it;
	// XXX TODO The following needs to be checked a bit: it may not be the best.
	result.first = (int) floor(fmin(it->second, log2(collection_size)));
	result.second = -1;
	env.end();
	return 1;
}
コード例 #25
0
ファイル: iloqpex2.cpp プロジェクト: annaPolytech/PRD
int
main (int argc, char **argv)
{
   IloEnv env;
   try {
      IloModel model(env);
      IloCplex cplex(env);

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

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

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

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

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

   env.end();
   return 0;
}  // END main
コード例 #26
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
コード例 #27
0
ファイル: ilodistmipex2.cpp プロジェクト: annaPolytech/PRD
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
コード例 #28
0
ファイル: etsp.cpp プロジェクト: renvieir/ioc
int
main(int argc, char** argv)
{
   IloEnv env;
   try {
      IloInt i, j;

      const char* filename;
      if (argc > 1)
         filename = argv[1];
      else
         filename = "../../../examples/data/etsp.dat";
      ifstream f(filename, ios::in);
      if (!f) {
         cerr << "No such file: " << filename << endl;
         throw(1);
      }

      IntMatrix   activityOnAResource(env);
      NumMatrix   duration(env);
      IloNumArray jobDueDate(env);
      IloNumArray jobEarlinessCost(env);
      IloNumArray jobTardinessCost(env);

      f >> activityOnAResource;
      f >> duration;
      f >> jobDueDate;
      f >> jobEarlinessCost;
      f >> jobTardinessCost;

      IloInt nbJob      = jobDueDate.getSize();
      IloInt nbResource = activityOnAResource.getSize();

      IloModel model(env);

      // Create start variables
      NumVarMatrix s(env, nbJob);
      for (j = 0; j < nbJob; j++) {
         s[j] = IloNumVarArray(env, nbResource, 0.0, Horizon);
      }

      // State precedence constraints
      for (j = 0; j < nbJob; j++) {
         for (i = 1; i < nbResource; i++) {
            model.add(s[j][i] >= s[j][i-1] + duration[j][i-1]);
         }
      }

      // State disjunctive constraints for each resource
      for (i = 0; i < nbResource; i++) {
         IloInt end = nbJob - 1;
         for (j = 0; j < end; j++) {
            IloInt a = activityOnAResource[i][j];
            for (IloInt k = j + 1; k < nbJob; k++) {
              IloInt b = activityOnAResource[i][k];
              model.add(s[j][a] >= s[k][b] + duration[k][b] ||
                        s[k][b] >= s[j][a] + duration[j][a]);
            }
         }
      }

      // The cost is the sum of earliness or tardiness costs of each job 
      IloInt last = nbResource - 1;
      IloExpr costSum(env);
      for (j = 0; j < nbJob; j++) {
         costSum += IloPiecewiseLinear(s[j][last] + duration[j][last],
            IloNumArray(env, 1, jobDueDate[j]),
            IloNumArray(env, 2, -jobEarlinessCost[j], jobTardinessCost[j]),
            jobDueDate[j], 0);
      }
      model.add(IloMinimize(env, costSum));
      costSum.end();

      IloCplex cplex(env);

      cplex.extract(model);

      cplex.setParam(IloCplex::Param::Emphasis::MIP, 4);

      if (cplex.solve()) {
          cout << "Solution status: " << cplex.getStatus() << endl;
          cout << " Optimal Value = " << cplex.getObjValue() << endl;
      }
   }
   catch (IloException& ex) {
      cerr << "Error: " << ex << endl;
   }
   catch (...) {
      cerr << "Error" << endl;
   }
   env.end();
   return 0;
}
コード例 #29
0
ファイル: eerstewerkend.cpp プロジェクト: ardgrauw/Thesis
int
main(int argc)
{


	IloEnv   env;
	try {
		IloModel model(env);

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

		populatebynonzero(model, varOutput, varHelp, cons);

		IloCplex cplex(model);

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

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

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


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

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

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

	env.end();
	cin.get();
	return 0;
}  // END main
コード例 #30
0
ファイル: CAP.cpp プロジェクト: tikhoncheva/work
int CProblem::setModel()
{
	//time_t start, end;

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

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

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

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

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

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

		}

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

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

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

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

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

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

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

	} // end try
	catch (IloException& e)
	{
		std::cerr << "Concert exception caught: " << e << std::endl;
	} catch (...)
	{
		std::cerr << "Unknown exception caught" << std::endl;
	}
	env.end();
	return 0;
}