本文整理汇总了C++中IloObjective类的典型用法代码示例。如果您正苦于以下问题:C++ IloObjective类的具体用法?C++ IloObjective怎么用?C++ IloObjective使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IloObjective类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: env
CPlexSolver::CPlexSolver(const Matrix& A, unsigned int lambda) :
env(), model(env), vars(env), constraints(env),
solutionVectors() {
// Add variables
for (int i = 0; i < A.shape()[1]; i++) {
vars.add(IloBoolVar(env)); // For simple t-designs
}
// Add constraints
for (int i = 0; i < A.shape()[0]; i++) {
constraints.add(IloRange(env, lambda, lambda)); // RHS = lambda in every equation
}
// Set up model to have as few block orbits as possible
IloObjective objective = IloMinimize(env);
for (int i = 0; i < A.shape()[1]; i++) {
objective.setLinearCoef(vars[i], 1);
}
// Set up constraints according to input matrix
for (int i = 0; i < A.shape()[0]; i++) {
for (int j = 0; j < A.shape()[1]; j++) {
constraints[i].setLinearCoef(vars[j], A[i][j]);
}
}
// TODO - names for constraints/vars may be necessary
// Might have to name these after the row/col labels for K-M Matrix
// Finish setting up the model
model.add(objective);
model.add(constraints);
}
示例2: IloModel
void BNC::buildModelNF(){
env = new IloEnv;
model = new IloModel(*env);
variables = new IloNumVarArray(*env);
constraints = new IloRangeArray(*env);
//create variables
for( int i = 0; i < n; ++i ){
variables->add( IloIntVar( *env, 0, 1 ) );
variables->add( IloIntVar( *env, 0, 1 ) );
}
for( int i = 0, k = 0; i < n; ++i ){
for( int j = i; j < n; ++j ){
if( graph[i][j] ){
IloRange newconstraintA( *env, 0, 1 );
IloRange newconstraintB( *env, 0, 1 );
newconstraintA.setLinearCoef( (*variables)[i], 1 );
newconstraintA.setLinearCoef( (*variables)[j], 1 );
newconstraintB.setLinearCoef( (*variables)[n+i], 1 );
newconstraintB.setLinearCoef( (*variables)[n+j], 1 );
constraints->add( newconstraintA );
constraints->add( newconstraintB );
++k;
}
}
}
for( int i = 0; i < n; ++i ){
IloRange newconstraintAB( *env, 0, 1 );
newconstraintAB.setLinearCoef( (*variables)[i], 1 );
newconstraintAB.setLinearCoef( (*variables)[n+i], 1 );
constraints->add( newconstraintAB );
}
//objective function
IloObjective obj = IloMaximize(*env);
//objective
for( int i = 0 ; i < n; i++ ){
obj.setLinearCoef((*variables)[i], 1 );
obj.setLinearCoef((*variables)[n+i], 1 );
}
model->add( *constraints );
model->add( obj );
cplex = new IloCplex(*model);
configureCPLEX();
//write model in file cplexmodel.lp
cplex->exportModel("cplexmodel.lp");
}
示例3: populatebynonzero
static void
populatebynonzero (IloModel model, IloIntVarArray x, IloRangeArray c)
{
IloEnv env = model.getEnv();
IloObjective obj = IloMaximize(env);
int n, a;
scanf("%d", &n);
scanf("%d", &a);
//restrição
c.add(IloRange(env, -IloInfinity, a));
//variaveis
for(int i=0 ; i<n; i++){
x.add(IloIntVar(env, 0, 1));
}
/*x.add(IloIntVar(env, 0.0, 40.0));
x.add(IloIntVar(env));
x.add(IloIntVar(env));*/
/*obj.setLinearCoef(x[0], 1.0);
obj.setLinearCoef(x[1], 2.0);
obj.setLinearCoef(x[2], 3.0);*/
/*restricoes*/
for(int i=0 ; i<n; i++){
scanf("%d", &a);
c[0].setLinearCoef(x[i], a);
}
//objetivo
for(int i=0 ; i<n; i++){
scanf("%d", &a);
obj.setLinearCoef(x[i], a);
}
/*c[0].setLinearCoef(x[1], 1.0);
c[0].setLinearCoef(x[2], 1.0);
c[1].setLinearCoef(x[0], 1.0);
c[1].setLinearCoef(x[1], -3.0);
c[1].setLinearCoef(x[2], 1.0);*/
c[0].setName("c1");
for(int i=0; i<n; i++){
char tmp[10];
printf("x%d", i+1);
x[i].setName(tmp);
}
model.add(obj);
model.add(c);
} // END populatebynonzero
示例4: populatebynonzero
static void
populatebynonzero(IloModel model, NumVarMatrix varOutput, NumVar3Matrix varHelp, Range3Matrix con)
{
IloEnv env = model.getEnv();
IloObjective obj = IloMaximize(env); //maximization function
for (int j = current; j < current + J; ++j)
{
for (int k = 0; k < K; ++k)
{
obj.setLinearCoef(varOutput[j][k], 1.0);//add all variables to objective function, factor 1
//constraint 0: express value of output objective variables
model.add(varOutput[j][k] + varHelp[j][k][2] - varHelp[j][k][3] == 0);
//constraint 1: Td2a>=+Td2b
model.add(varHelp[j][k][5] - varHelp[j][k][4] >= 0);
//constraint 2: Tj>=Td2a + Tdc + Tblow
model.add(varHelp[j][k][5] <= T[j] - Tdc - Tblow[j] - Tslack);
//constraint 3: Td2b = Tfa+Tfd
model.add(Tfd[k] == varHelp[j][k][4] - varHelp[j][k][3]);
//constraint 4: Td1a >= Td1b
model.add(0 <= varHelp[j][k][1] - varHelp[j][k][0]);
//constraint 5: Tfb >= Td1a+Tdf
model.add(Tdf[k] <= varHelp[j][k][2] - varHelp[j][k][1]);
//constraint 6: Td1b = T(j-a)+Tcd
model.add(T[j - a[k]] + Tcd == varHelp[j][k][0]);
//constraint 7: Td1a >= Td2b(j-b) + Tloss, 1
model.add(TlossD[k] <= varHelp[j][k][1] - varHelp[j - b[k]][k][4]);
//constraint 8: Tfb >= Tfa(j-1)+Tloss, 2
model.add(TlossF[k] <= varHelp[j][k][2] - varHelp[j - 1][k][3]);
//constraint 9: at least X s for every load
model.add(varOutput[j][k] >= TloadMin[k]);
}
//constraint 10: both spoons are picked up at same time at dropoff: Td2a,1 == Td2a,2
model.add(varHelp[j][1][5] == varHelp[j][0][5]);
}
model.add(obj);
}
示例5: generateProblem
void generateProblem(const ILPModel& m, IloModel& model, IloNumVarArray& x, IloRangeArray& con) {
IloEnv env = model.getEnv();
IloObjective obj = (m.obj == MINIMIZE ? IloMinimize(env) : IloMaximize(env));
for (unsigned long v = 0; v < m.numberOfVariables(); ++v) {
switch (m.x[v].type) {
case FLT:
x.add(IloNumVar(env, m.x[v].lowerBound, m.x[v].upperBound, IloNumVar::Float));
break;
case BIN:
x.add(IloNumVar(env, m.x[v].lowerBound, m.x[v].upperBound, IloNumVar::Bool));
break;
default:
x.add(IloNumVar(env, m.x[v].lowerBound, m.x[v].upperBound, IloNumVar::Int));
}
obj.setLinearCoef(x[v], m.c[v]);
x[v].setName(m.varDesc[v].c_str());
}
for (unsigned long c = 0; c < m.numberOfConstraints(); ++c) {
switch (m.ops[c]) {
case LESS_EQUAL:
con.add(IloRange(env, -IloInfinity, m.b[c]));
break;
case EQUAL:
con.add(IloRange(env, m.b[c], m.b[c]));
break;
case GREATER_EQUAL:
con.add(IloRange(env, m.b[c], IloInfinity));
}
for (const pair<uint32_t, double>& p : m.A[c])
con[c].setLinearCoef(x[p.first], p.second);
con[c].setName(m.conDesc[c].c_str());
}
model.add(obj);
model.add(con);
}
示例6: main
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
示例7: separate
// This routine separates Benders' cuts violated by the current x solution.
// Violated cuts are found by solving the worker LP
//
IloBool
separate(const Arcs x, const IloNumArray2 xSol, IloCplex cplex,
const IloNumVarArray v, const IloNumVarArray u,
IloObjective obj, IloExpr cutLhs, IloNum& cutRhs)
{
IloBool violatedCutFound = IloFalse;
IloEnv env = cplex.getEnv();
IloModel mod = cplex.getModel();
IloInt numNodes = xSol.getSize();
IloInt numArcs = numNodes * numNodes;
IloInt i, j, k, h;
// Update the objective function in the worker LP:
// minimize sum(k in V0) sum((i,j) in A) x(i,j) * v(k,i,j)
// - sum(k in V0) u(k,0) + sum(k in V0) u(k,k)
mod.remove(obj);
IloExpr objExpr = obj.getExpr();
objExpr.clear();
for (k = 1; k < numNodes; ++k) {
for (i = 0; i < numNodes; ++i) {
for (j = 0; j < numNodes; ++j) {
objExpr += xSol[i][j] * v[(k-1)*numArcs + i*numNodes + j];
}
}
}
for (k = 1; k < numNodes; ++k) {
objExpr += u[(k-1)*numNodes + k];
objExpr -= u[(k-1)*numNodes];
}
obj.setExpr(objExpr);
mod.add(obj);
objExpr.end();
// Solve the worker LP
cplex.solve();
// A violated cut is available iff the solution status is Unbounded
if ( cplex.getStatus() == IloAlgorithm::Unbounded ) {
IloInt vNumVars = (numNodes-1) * numArcs;
IloNumVarArray var(env);
IloNumArray val(env);
// Get the violated cut as an unbounded ray of the worker LP
cplex.getRay(val, var);
// Compute the cut from the unbounded ray. The cut is:
// sum((i,j) in A) (sum(k in V0) v(k,i,j)) * x(i,j) >=
// sum(k in V0) u(k,0) - u(k,k)
cutLhs.clear();
cutRhs = 0.;
for (h = 0; h < val.getSize(); ++h) {
IloInt *index_p = (IloInt*) var[h].getObject();
IloInt index = *index_p;
if ( index >= vNumVars ) {
index -= vNumVars;
k = index / numNodes + 1;
i = index - (k-1)*numNodes;
if ( i == 0 )
cutRhs += val[h];
else if ( i == k )
cutRhs -= val[h];
}
else {
k = index / numArcs + 1;
i = (index - (k-1)*numArcs) / numNodes;
j = index - (k-1)*numArcs - i*numNodes;
cutLhs += val[h] * x[i][j];
}
}
var.end();
val.end();
violatedCutFound = IloTrue;
}
return violatedCutFound;
} // END separate
示例8: createWorkerLP
// This routine set up the IloCplex algorithm to solve the worker LP, and
// creates the worker LP (i.e., the dual of flow constraints and
// capacity constraints of the flow MILP)
//
// Modeling variables:
// forall k in V0, i in V:
// u(k,i) = dual variable associated with flow constraint (k,i)
//
// forall k in V0, forall (i,j) in A:
// v(k,i,j) = dual variable associated with capacity constraint (k,i,j)
//
// Objective:
// minimize sum(k in V0) sum((i,j) in A) x(i,j) * v(k,i,j)
// - sum(k in V0) u(k,0) + sum(k in V0) u(k,k)
//
// Constraints:
// forall k in V0, forall (i,j) in A: u(k,i) - u(k,j) <= v(k,i,j)
//
// Nonnegativity on variables v(k,i,j)
// forall k in V0, forall (i,j) in A: v(k,i,j) >= 0
//
void
createWorkerLP(IloCplex cplex, IloNumVarArray v, IloNumVarArray u,
IloObjective obj, IloInt numNodes)
{
IloInt i, j, k;
IloEnv env = cplex.getEnv();
IloModel mod(env, "atsp_worker");
// Set up IloCplex algorithm to solve the worker LP
cplex.extract(mod);
cplex.setOut(env.getNullStream());
// Turn off the presolve reductions and set the CPLEX optimizer
// to solve the worker LP with primal simplex method.
cplex.setParam(IloCplex::Reduce, 0);
cplex.setParam(IloCplex::RootAlg, IloCplex::Primal);
// Create variables v(k,i,j) forall k in V0, (i,j) in A
// For simplicity, also dummy variables v(k,i,i) are created.
// Those variables are fixed to 0 and do not partecipate to
// the constraints.
IloInt numArcs = numNodes * numNodes;
IloInt vNumVars = (numNodes-1) * numArcs;
IloNumVarArray vTemp(env, vNumVars, 0, IloInfinity);
for (k = 1; k < numNodes; ++k) {
for (i = 0; i < numNodes; ++i) {
vTemp[(k-1)*numArcs + i *numNodes + i].setBounds(0, 0);
}
}
v.clear();
v.add(vTemp);
vTemp.end();
mod.add(v);
// Set names for variables v(k,i,j)
for (k = 1; k < numNodes; ++k) {
for(i = 0; i < numNodes; ++i) {
for(j = 0; j < numNodes; ++j) {
char varName[100];
sprintf(varName, "v.%d.%d.%d", (int) k, (int) i, (int) j);
v[(k-1)*numArcs + i*numNodes + j].setName(varName);
}
}
}
// Associate indices to variables v(k,i,j)
IloIntArray vIndex(env, vNumVars);
for (j = 0; j < vNumVars; ++j)
{
vIndex[j] = j;
v[j].setObject(&vIndex[j]);
}
// Create variables u(k,i) forall k in V0, i in V
IloInt uNumVars = (numNodes-1) * numNodes;
IloNumVarArray uTemp(env, uNumVars, -IloInfinity, IloInfinity);
u.clear();
u.add(uTemp);
uTemp.end();
mod.add(u);
// Set names for variables u(k,i)
for (k = 1; k < numNodes; ++k) {
for(i = 0; i < numNodes; ++i) {
char varName[100];
sprintf(varName, "u.%d.%d", (int) k, (int) i);
u[(k-1)*numNodes + i].setName(varName);
}
}
// Associate indices to variables u(k,i)
//.........这里部分代码省略.........
示例9: x
/** Separation function.
* This function is invoked whenever CPLEX finds an integer feasible
* solution. It then separates either feasibility or optimality cuts
* on this solution.
*/
void BendersOpt::LazyConstraintCallback::main() {
std::cout << "Callback invoked. Separate Benders cuts." << std::endl;
IloNumArray x(getEnv());
IloNumArray rayVals(getEnv());
IloNumVarArray rayVars(getEnv());
IloNumArray cutVal(getEnv());
IloNumVarArray cutVar(getEnv());
getValues(x, master->vars);
bool error = false;
// Iterate over blocks and trigger a separation on each of them.
// The separation is triggered asynchronously so that it can happen
// on different remote objects simultaneously.
for (BlockVector::size_type b = 0; b < blocks.size(); ++b) {
Block *const block = blocks[b];
// Remove current objective from the block's model.
IloModel model = block->cplex.getModel();
IloObjective obj = block->obj;
model.remove(obj);
IloExpr newObj = obj.getExpr();
// Iterate over the fixed master variables in this block to update
// the block's objective function.
// Each fixed variable goes to the right-hand side and therefore
// into the objective function.
for (std::vector<Block::FixData>::const_iterator it = block->fixed.begin(); it != block->fixed.end(); ++it)
newObj -= block->vars[it->row] * (it->val * x[it->col]);
obj.setExpr(newObj);
model.add(obj);
newObj.end();
// If the problem is unbounded we need to get an infinite ray in
// order to be able to generate the respective Benders cut. If
// CPLEX proves unboundedness in presolve then it will return
// CPX_STAT_INForUNBD and no ray will be available. So we need to
// disable presolve.
block->cplex.setParam(IloCplex::Param::Preprocessing::Presolve, false);
block->cplex.setParam(IloCplex::Param::Preprocessing::Reduce, 0);
// Solve the updated problem to optimality.
block->cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Primal);
try {
handles[b] = block->cplex.solve(true);
} catch (...) {
// If there is an exception then we need to kill and join
// all remaining solves. Otherwise we may leak handles.
while (--b > 0) {
handles[b].kill();
handles[b].join();
}
throw;
}
}
// Wait for the various LP solves to complete.
for (BlockVector::size_type b = 0; b < blocks.size(); ++b)
handles[b].join();
// See if we need to generate cuts.
for (BlockVector::size_type b = 0; b < blocks.size(); ++b) {
Block *const block = blocks[b];
cutVal.clear();
cutVar.clear();
double cutlb = -IloInfinity;
double cutub = IloInfinity;
// We ust STL types here since they are exception safe.
std::vector<double> tmp(master->vars.getSize(), 0);
std::map<IloNumVar,double,ExtractableLess<IloNumVar> > rayMap;
// Depending on the status either seperate a feasibility or an
// optimality cut.
switch (block->cplex.getStatus()) {
case IloAlgorithm::Unbounded:
{
// The subproblem is unbounded. We need to extract a feasibility
// cut from an unbounded ray of the problem (see also the comments
// at the top of this file).
std::cout << "unbounded ";
block->cplex.getRay(rayVals, rayVars);
cutub = 0.0;
for (IloInt j = 0; j < rayVars.getSize(); ++j) {
cutub -= rayVals[j] * block->objMap[rayVars[j]];
rayMap[rayVars[j]] = rayVals[j];
}
for (std::vector<Block::FixData>::const_iterator it = block->fixed.begin(); it != block->fixed.end(); ++it)
tmp[it->col] -= it->val * rayMap[block->vars[it->row]];
for (IloInt j = 0; j < master->vars.getSize(); ++j) {
if ( fabs (tmp[j]) > 1e-6 ) {
cutVar.add(master->vars[j]);
cutVal.add(tmp[j]);
//.........这里部分代码省略.........
示例10: main
ILOSTLBEGIN
int main(int argc, char **argv)
{
IloEnv env;
try
{
IloArray<IloNumArray> distance(env);
//Model Initialization
IloModel model(env);
//Taking Data from Distance Data File
ifstream in;
in.open("carpool-data.txt",ios::in);
in >> distance;
in.close();
cout<<distance<<endl;
//2D Array for Results
IloArray<IloNumArray> X_val(env, 7);
for (int i = 0; i < 7; i++)
{
X_val[i] = IloNumArray(env,7);
}
IloArray<IloNumArray> Y_val(env, 7);
for (int i = 0; i < 7; i++)
{
Y_val[i] = IloNumArray(env,7);
}
//2D Array for Xij
IloArray<IloNumVarArray> X(env, 7);
for (int i = 0; i < 7; i++)
{
X[i] = IloNumVarArray(env,7,0,1,ILOINT);
}
//2D Array for Yij
IloArray<IloNumVarArray> Y(env, 7);
for (int i = 0; i < 7; i++)
{
Y[i] = IloNumVarArray(env,7,0,1,ILOINT);
}
// 1D array for Ui and U-val
//IloNumVarArray U(env,7,0,7,ILOINT);
//IloNumArray U_val(env,7);
// Defining Obj to be equal to sum-product(Dij*Xij + Dij*Yij)
IloExpr Obj(env);
for (int i = 0; i < 7; ++i)
{
for (int j = 0; j < 7; j++)
{
if(i != j)
{
Obj += distance[i][j]*X[i][j] + distance[i][j]*Y[i][j];
}
}
}
//model.add(IloMaximize(env,Obj)); // IloMinimize is used for minimization problems
//Alternatively, model.add(IloMaximize(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();
//Constraints for the model
//One Input per Node except Office
IloExpr Input(env);
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 7; j++)
{
if(i != j )
{
Input += X[i][j] + Y[i][j];
}
}
model.add(Input == 1);
}
Input.end();
//One Output per Node except Office
IloExpr Output(env);
for (int j = 0; j < 6; j++)
{
for (int i = 0; i < 7; i++)
{
if(i != j )
{
Output += X[i][j] + Y[i][j];
}
}
//.........这里部分代码省略.........
示例11: main
int
main(int argc, char **argv)
{
IloEnv env;
try {
IloInt i, j;
IloNum rollWidth;
IloNumArray amount(env);
IloNumArray size(env);
if ( argc > 1 )
readData(argv[1], rollWidth, size, amount);
else
readData("../../../examples/data/cutstock.dat",
rollWidth, size, amount);
/// CUTTING-OPTIMIZATION PROBLEM ///
IloModel cutOpt (env);
IloObjective RollsUsed = IloAdd(cutOpt, IloMinimize(env));
IloRangeArray Fill = IloAdd(cutOpt,
IloRangeArray(env, amount, IloInfinity));
IloNumVarArray Cut(env);
IloInt nWdth = size.getSize();
for (j = 0; j < nWdth; j++) {
Cut.add(IloNumVar(RollsUsed(1) + Fill[j](int(rollWidth / size[j]))));
}
IloCplex cutSolver(cutOpt);
/// PATTERN-GENERATION PROBLEM ///
IloModel patGen (env);
IloObjective ReducedCost = IloAdd(patGen, IloMinimize(env, 1));
IloNumVarArray Use(env, nWdth, 0.0, IloInfinity, ILOINT);
patGen.add(IloScalProd(size, Use) <= rollWidth);
IloCplex patSolver(patGen);
/// COLUMN-GENERATION PROCEDURE ///
IloNumArray price(env, nWdth);
IloNumArray newPatt(env, nWdth);
/// COLUMN-GENERATION PROCEDURE ///
for (;;) {
/// OPTIMIZE OVER CURRENT PATTERNS ///
cutSolver.solve();
report1 (cutSolver, Cut, Fill);
/// FIND AND ADD A NEW PATTERN ///
for (i = 0; i < nWdth; i++) {
price[i] = -cutSolver.getDual(Fill[i]);
}
ReducedCost.setLinearCoefs(Use, price);
patSolver.solve();
report2 (patSolver, Use, ReducedCost);
if (patSolver.getValue(ReducedCost) > -RC_EPS) break;
patSolver.getValues(newPatt, Use);
Cut.add( IloNumVar(RollsUsed(1) + Fill(newPatt)) );
}
cutOpt.add(IloConversion(env, Cut, ILOINT));
cutSolver.solve();
cout << "Solution status: " << cutSolver.getStatus() << endl;
report3 (cutSolver, Cut);
}
catch (IloException& ex) {
cerr << "Error: " << ex << endl;
}
catch (...) {
cerr << "Error" << endl;
}
env.end();
return 0;
}
示例12: Worker
/** Create a new worker.
* The constructor mainly does the following:
* - create an IloCplex instance that refers to a remote worker,
* - load the model in <code>modelfile</code>,
* - setup parameters depending on this worker's index,
* - start an asynchronous solve.
* If anything fails then an exception will be thrown.
* @param env The environment used for instantiating Ilo* objects.
* @param i The index of the worker to be created. This also
* determines the parameter settings to use in this worker.
* @param s A pointer to the global solve state.
* @param transport The transport name for the IloCplex constructor.
* @param argc The argument count for the IloCplex constructor.
* @param argv The array of transport arguments for the IloCplex
* constructor.
* @param modelfile Name of the model to be loaded into the worker.
* @param output The output mode.
* @param objdiff The minimal difference between so that two
* consecutive objective function values are considered
* different.
*/
Worker(IloEnv env, int i, SolveState *s, char const *transport,
int argc, char const **argv, char const *modelfile,
OUTPUT output, double objdiff)
: idx(i), state(s), model(env), cplex(0), handle(0),
primal(IloInfinity), dual(-IloInfinity),
obj(env), x(env), rng(env), infoHandler(this), outb(idx), outs(&outb)
{
try {
// Create remote object, setup output and load the model.
cplex = IloCplex(model, transport, argc, argv);
switch (output) {
case OUTPUT_SILENT:
// Disable output on the output and warning stream.
cplex.setOut(env.getNullStream());
cplex.setWarning(env.getNullStream());
break;
case OUTPUT_PREFIXED:
// Redirect output to our custom stream.
cplex.setOut(outs);
cplex.setWarning(outs);
break;
case OUTPUT_LOG:
// Nothing to do here. By default output is enabled.
break;
}
cplex.importModel(model, modelfile, obj, x, rng);
if ( obj.getSense() == IloObjective::Minimize ) {
primal = -IloInfinity;
dual = IloInfinity;
}
// We set the thread count for each solver to 1 so that we do not
// run into problems if multiple solves are performed on the same
// machine.
cplex.setParam(IloCplex::Param::Threads, 1);
// Each worker runs with a different random seed. This way we
// get different paths through the tree even if the other
// parameter settings are the same.
cplex.setParam(IloCplex::Param::RandomSeed, idx);
// Apply parameter settings.
for (class ParamValue const *vals = settings[idx % NUMSETTINGS].values;
vals->isValid(); ++vals)
vals->apply(cplex);
// Install callback and set objective change.
int status = cplex.userfunction (USERACTION_ADDCALLBACK,
0, NULL, 0, 0, NULL);
if ( status )
throw status;
IloCplex::Serializer s;
s.add(objdiff);
status = cplex.userfunction (USERACTION_CHANGEOBJDIFF,
s.getRawLength(), s.getRawData(),
0, 0, NULL);
if ( status )
throw status;
// Register the handler that will process info messages sent
// from the worker.
cplex.setRemoteInfoHandler(&infoHandler);
// Everything is setup. Launch the asynchronous solve.
handle = cplex.solve(true);
} catch (...) {
// In case of an exception we need to take some special
// cleanup actions. Note that if we get here then the
// solve cannot have been started and we don't need to
// kill or join the asynchronous solve.
if ( cplex.getImpl() )
cplex.end();
rng.end();
x.end();
obj.end();
model.end();
throw;
}
}
示例13: main
int
main (int argc, char **argv)
{
int result = 0;
IloEnv env;
try {
static int indices[] = { 0, 1, 2, 3, 4, 5, 6 };
IloModel model(env);
/* ***************************************************************** *
* *
* S E T U P P R O B L E M *
* *
* The model we setup here is *
* Minimize *
* obj: 3x1 - x2 + 3x3 + 2x4 + x5 + 2x6 + 4x7 *
* Subject To *
* c1: x1 + x2 = 4 *
* c2: x1 + x3 >= 3 *
* c3: x6 + x7 <= 5 *
* c4: -x1 + x7 >= -2 *
* q1: [ -x1^2 + x2^2 ] <= 0 *
* q2: [ 4.25x3^2 -2x3*x4 + 4.25x4^2 - 2x4*x5 + 4x5^2 ] + 2 x1 <= 9.0
* q3: [ x6^2 - x7^2 ] >= 4 *
* Bounds *
* 0 <= x1 <= 3 *
* x2 Free *
* 0 <= x3 <= 0.5 *
* x4 Free *
* x5 Free *
* x7 Free *
* End *
* *
* ***************************************************************** */
IloNumVarArray x(env);
x.add(IloNumVar(env, 0, 3, "x1"));
x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x2"));
x.add(IloNumVar(env, 0, 0.5, "x3"));
x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x4"));
x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x5"));
x.add(IloNumVar(env, 0, IloInfinity, "x6"));
x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x7"));
for (IloInt i = 0; i < x.getSize(); ++i)
x[i].setObject(&indices[i]);
IloObjective obj = IloMinimize(env,
3*x[0] - x[1] + 3*x[2] + 2*x[3] +
x[4] + 2*x[5] + 4*x[6], "obj");
model.add(obj);
IloRangeArray linear(env);
linear.add(IloRange(env, 4.0, x[0] + x[1], 4.0, "c1"));
linear.add(IloRange(env, 3.0, x[0] + x[2], IloInfinity, "c2"));
linear.add(IloRange(env, -IloInfinity, x[5] + x[6], 5.0, "c3"));
linear.add(IloRange(env, -2.0, -x[0] + x[6], IloInfinity, "c4"));
for (IloInt i = 0; i < linear.getSize(); ++i)
linear[i].setObject(&indices[i]);
model.add(linear);
IloRangeArray quad(env);
quad.add(IloRange(env, -IloInfinity, -x[0]*x[0] + x[1] * x[1], 0, "q1"));
quad.add(IloRange(env, -IloInfinity,
4.25*x[2]*x[2] - 2*x[2]*x[3] + 4.25*x[3]*x[3] +
-2*x[3]*x[4] + 4*x[4]*x[4] + 2*x[0],
9.0, "q2"));
quad.add(IloRange(env, 4.0, x[5]*x[5] - x[6]*x[6], IloInfinity, "q3"));
for (IloInt i = 0; i < quad.getSize(); ++i)
quad[i].setObject(&indices[i]);
model.add(quad);
/* ***************************************************************** *
* *
* O P T I M I Z E P R O B L E M *
* *
* ***************************************************************** */
IloCplex cplex(model);
cplex.setParam(IloCplex::Param::Barrier::QCPConvergeTol, 1e-10);
cplex.solve();
/* ***************************************************************** *
* *
* Q U E R Y S O L U T I O N *
* *
* ***************************************************************** */
IloNumArray xval(env);
IloNumArray slack(env);
IloNumArray qslack(env);
IloNumArray cpi(env);
IloNumArray rpi(env);
IloNumArray qpi;
cplex.getValues(x, xval);
cplex.getSlacks(slack, linear);
cplex.getSlacks(qslack, quad);
cplex.getReducedCosts(cpi, x);
cplex.getDuals(rpi, linear);
qpi = getqconstrmultipliers(cplex, xval, quad);
//.........这里部分代码省略.........
示例14: c
void Instance::optKara2007()
{
CPUTimer t;
t.start();
int size = Gifts.size();
double totalWeight = 0;
for (int i = 0; i < (int)Gifts.size(); i++)
{
totalWeight += Gifts[i].weight;
}
cout << "Optimizing Instance by Kara2007 Two-Index One-Commodity Flow Integer Model to CPLEX..." << endl;
cout << "Number of Gifts:\t" << size << endl;
vector<vector<double> > c(size+1);
for (int i = 0; i < size+1; i++)
{
c[i].resize(size+1);
}
for (int i = 0; i < size+1; i++)
{
for (int j = i+1; j < size+1; j++)
{
c[i][j] = getDistance(getGiftId(i), getGiftId(j));
c[j][i] = c[i][j];
}
}
IloEnv env;
IloModel model(env);
IloObjective obj = IloMinimize(env);
NumVarMatrix var_x(env);
NumVarMatrix var_f(env);
string varName;
string consName;
for (int i = 0; i < size+1; i++)
{
var_x.add(IloNumVarArray(env));
var_f.add(IloNumVarArray(env));
}
varName = "K";
IloNumVar var_K(env, 1, size, IloNumVar::Int, (char*)varName.c_str());
for (int i = 0; i < size+1; i++)
{
for (int j = 0; j < size+1; j++)
{
varName = "x" + to_string(getGiftId(i)) + "_" + to_string(getGiftId(j));
var_x[i].add( IloNumVar(env, 0, 1, IloNumVar::Int, (char*)varName.c_str()) );
varName = "f" + to_string(getGiftId(i)) + "_" + to_string(getGiftId(j));
var_f[i].add( IloNumVar(env, 0, 1010, IloNumVar::Float, (char*)varName.c_str()) );
}
}
for (int i = 0; i < size+1; i++)
{
for (int j = 0; j < size+1; j++)
{
obj.setLinearCoef(var_x[i][j], 10*c[i][j]);
obj.setLinearCoef(var_f[i][j], c[i][j]);
}
}
model.add(obj);
//numeracao segundo Fukasawa 2015
// (1a) - tudo que sai de todo i
for (int i = 0; i < size; i++)
{
consName = "c1a_" + to_string(getGiftId(i));
IloRange c1a(env, 1, 1, (char*)consName.c_str());
for (int j = 0; j < size+1; j++)
{
if (c[i][j] > 0)
{
c1a.setLinearCoef(var_x[i][j], 1);
}
}
model.add(c1a);
}
// (1b) - tudo que entra em todo i
for (int i = 0; i < size; i++)
{
consName = "c1b_" + to_string(getGiftId(i));
IloRange c1b( env, 1, 1, (char*)consName.c_str() );
for (int j = 0; j < size+1; j++)
{
if (c[i][j] > 0)
{
c1b.setLinearCoef(var_x[j][i], 1);
}
}
//.........这里部分代码省略.........
示例15: getObjectiveSense
/** Get the objective sense for this worker's objective. */
IloObjective::Sense getObjectiveSense() const { return obj.getSense(); }