GUROBISolver.cc 31.4 KB
Newer Older
David Bommes's avatar
David Bommes committed
1
2
3
4
5
6
7
8
9
10
11
12
//=============================================================================
//
//  CLASS GUROBISolver - IMPLEMENTATION
//
//=============================================================================

//== INCLUDES =================================================================

//== COMPILE-TIME PACKAGE REQUIREMENTS ========================================
#include <CoMISo/Config/config.hh>
#if COMISO_GUROBI_AVAILABLE
//=============================================================================
13
 #include <gurobi_c++.h>
David Bommes's avatar
David Bommes committed
14
15

#include "GUROBISolver.hh"
16
17
18
19
#if (COMISO_QT_AVAILABLE)
#include "GurobiHelper.hh"
#endif//COMISO_QT_AVAILABLE
#include <CoMISo/Utils/CoMISoError.hh>
Max Lyon's avatar
Max Lyon committed
20
#include <CoMISo/Utils/StopWatch.hh>
21

David Bommes's avatar
David Bommes committed
22

23
#include <Base/Debug/DebTime.hh>
24
25
#include <stdexcept>

David Bommes's avatar
David Bommes committed
26
27
28
29
30
31
32
//== NAMESPACES ===============================================================

namespace COMISO {

//== IMPLEMENTATION ========================================================== 


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
void add_constraint_to_model(COMISO::NConstraintInterface* _constraint, 
  GRBModel& _model, std::vector<GRBVar>& _vars, const double* _x)
{
  DEB_enter_func;
  DEB_warning_if(!_constraint->is_linear(), 1,
     "GUROBISolver received a problem with non-linear constraints!!!\n");

  GRBLinExpr lin_expr;
  NConstraintInterface::SVectorNC gc;
  _constraint->eval_gradient(_x, gc);

  NConstraintInterface::SVectorNC::InnerIterator v_it(gc);
  for(; v_it; ++v_it)
    lin_expr += _vars[v_it.index()]*v_it.value();

  double b = _constraint->eval_constraint(_x);

  switch(_constraint->constraint_type())
  {
    case NConstraintInterface::NC_EQUAL         : _model.addConstr(lin_expr + b == 0); break;
    case NConstraintInterface::NC_LESS_EQUAL    : _model.addConstr(lin_expr + b <= 0); break;
    case NConstraintInterface::NC_GREATER_EQUAL : _model.addConstr(lin_expr + b >= 0); break;
  }
}


//-----------------------------------------------------------------------------

David Bommes's avatar
David Bommes committed
61

62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
static void process_gurobi_exception(const GRBException& _exc)
{
  DEB_enter_func;
  DEB_error("Gurobi exception error code = " << _exc.getErrorCode() << 
    " and message: [" << _exc.getMessage() << "]");
    
  // NOTE: we could propagate e.getMessage() either using std::exception, 
  // or a specialized Reform exception type

  // The GRB_ error codes are defined in gurobi_c.h Gurobi header. 
  switch (_exc.getErrorCode())
  {
  case GRB_ERROR_NO_LICENSE: 
    COMISO_THROW(GUROBI_LICENCE_ABSENT); 
  case GRB_ERROR_SIZE_LIMIT_EXCEEDED: 
    COMISO_THROW(GUROBI_LICENCE_MODEL_TOO_LARGE); break;
  default: 
    COMISO_THROW(UNSPECIFIED_GUROBI_EXCEPTION);
  }
}
82

David Bommes's avatar
David Bommes committed
83
84
85
bool
GUROBISolver::
solve(NProblemInterface*                  _problem,
86
87
      const std::vector<NConstraintInterface *> &_constraints,
      const std::vector<PairIndexVtype> &_discrete_constraints,
David Bommes's avatar
David Bommes committed
88
89
      const double                        _time_limit)
{
90
  DEB_enter_func;
David Bommes's avatar
David Bommes committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
  try
  {
    //----------------------------------------------
    // 0. set up environment
    //----------------------------------------------

    GRBEnv   env   = GRBEnv();
    GRBModel model = GRBModel(env);

    model.getEnv().set(GRB_DoubleParam_TimeLimit, _time_limit);


    //----------------------------------------------
    // 1. allocate variables
    //----------------------------------------------

    // determine variable types: 0->real, 1->integer, 2->bool
    std::vector<char> vtypes(_problem->n_unknowns(),0);
    for(unsigned int i=0; i<_discrete_constraints.size(); ++i)
      switch(_discrete_constraints[i].second)
      {
        case Integer: vtypes[_discrete_constraints[i].first] = 1; break;
        case Binary : vtypes[_discrete_constraints[i].first] = 2; break;
        default     : break;
      }

    // GUROBI variables
    std::vector<GRBVar> vars;
    // first all
    for( int i=0; i<_problem->n_unknowns(); ++i)
      switch(vtypes[i])
      {
        case 0 : vars.push_back( model.addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_CONTINUOUS) ); break;
        case 1 : vars.push_back( model.addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_INTEGER   ) ); break;
        case 2 : vars.push_back( model.addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_BINARY    ) ); break;
      }

Max Lyon's avatar
Max Lyon committed
128
129
130
131
132
133
    // set start
    std::vector<double> start(vars.size());
    _problem->initial_x(start.data());

    for (int i = 0; i < _problem->n_unknowns(); ++i)
      vars[i].set(GRB_DoubleAttr_Start, start[i]);
David Bommes's avatar
David Bommes committed
134
135
136
137
138
139
140
141
142
143
144
145
146

    // Integrate new variables
    model.update();

    //----------------------------------------------
    // 2. setup constraints
    //----------------------------------------------

    // get zero vector
    std::vector<double> x(_problem->n_unknowns(), 0.0);

    for(unsigned int i=0; i<_constraints.size();  ++i)
    {
147
148
      DEB_warning_if(!_constraints[i]->is_linear(), 1,
        "GUROBISolver received a problem with non-linear constraints!!!");
David Bommes's avatar
David Bommes committed
149
150
151
152
153
154
155

      GRBLinExpr lin_expr;
      NConstraintInterface::SVectorNC gc;
      _constraints[i]->eval_gradient(P(x), gc);

      NConstraintInterface::SVectorNC::InnerIterator v_it(gc);
      for(; v_it; ++v_it)
156
        lin_expr += vars[v_it.index()]*v_it.value();
David Bommes's avatar
David Bommes committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172

      double b = _constraints[i]->eval_constraint(P(x));

      switch(_constraints[i]->constraint_type())
      {
        case NConstraintInterface::NC_EQUAL         : model.addConstr(lin_expr + b == 0); break;
        case NConstraintInterface::NC_LESS_EQUAL    : model.addConstr(lin_expr + b <= 0); break;
        case NConstraintInterface::NC_GREATER_EQUAL : model.addConstr(lin_expr + b >= 0); break;
      }
    }
    model.update();

    //----------------------------------------------
    // 3. setup energy
    //----------------------------------------------

173
174
    DEB_warning_if(!_problem->constant_hessian(), 1, 
      "GUROBISolver received a problem with non-constant hessian!!!");
David Bommes's avatar
David Bommes committed
175
176
177
178
179
180
181

    GRBQuadExpr objective;

    // add quadratic part
    NProblemInterface::SMatrixNP H;
    _problem->eval_hessian(P(x), H);
    for( int i=0; i<H.outerSize(); ++i)
182
    {
David Bommes's avatar
David Bommes committed
183
184
      for (NProblemInterface::SMatrixNP::InnerIterator it(H,i); it; ++it)
        objective += 0.5*it.value()*vars[it.row()]*vars[it.col()];
185
    }
David Bommes's avatar
David Bommes committed
186
187
188
189
190
191
192
193
194
195
196
197

    // add linear part
    std::vector<double> g(_problem->n_unknowns());
    _problem->eval_gradient(P(x), P(g));
    for(unsigned int i=0; i<g.size(); ++i)
      objective += g[i]*vars[i];

    // add constant part
    objective += _problem->eval_f(P(x));

    model.set(GRB_IntAttr_ModelSense, 1);
    model.setObjective(objective);
198
    model.update();
David Bommes's avatar
David Bommes committed
199

David Bommes's avatar
David Bommes committed
200

David Bommes's avatar
David Bommes committed
201
202
203
204
    //----------------------------------------------
    // 4. solve problem
    //----------------------------------------------

David Bommes's avatar
David Bommes committed
205
206
207
208
209
210
211
212

    if (solution_input_path_.empty())
    {
      if (!problem_env_output_path_.empty())
      {
        std::cout << "Writing problem's environment into file \"" << problem_env_output_path_ << "\"." << std::endl;
        model.getEnv().writeParams(problem_env_output_path_);
      }
213
214

#if (COMISO_QT_AVAILABLE)
David Bommes's avatar
David Bommes committed
215
216
217
218
219
      if (!problem_output_path_.empty())
      {
        std::cout << "Writing problem into file \"" << problem_output_path_ << "\"." << std::endl;
        GurobiHelper::outputModelToMpsGz(model, problem_output_path_);
      }
220
#endif//COMISO_QT_AVAILABLE
David Bommes's avatar
David Bommes committed
221
222
223
224
      model.optimize();
    }
    else
    {
225
      DEB_line(2, "Reading solution from file \"" << solution_input_path_)
David Bommes's avatar
David Bommes committed
226
227
    }

David Bommes's avatar
David Bommes committed
228
229
230
231
    //----------------------------------------------
    // 5. store result
    //----------------------------------------------

David Bommes's avatar
David Bommes committed
232
233
234
235
236
237
238
239
    if (solution_input_path_.empty())
    {
      // store computed result
      for(unsigned int i=0; i<vars.size(); ++i)
        x[i] = vars[i].get(GRB_DoubleAttr_X);
    }
    else
    {
240
#if (COMISO_QT_AVAILABLE)
241
242
243
244
245
246
247
248
249
        std::cout << "Loading stored solution from \"" << solution_input_path_ << "\"." << std::endl;
        // store loaded result
        const size_t oldSize = x.size();
        x.clear();
        GurobiHelper::readSolutionVectorFromSOL(x, solution_input_path_);
        if (oldSize != x.size()) {
            std::cerr << "oldSize != x.size() <=> " << oldSize << " != " << x.size() << std::endl;
            throw std::runtime_error("Loaded solution vector doesn't have expected dimension.");
        }
250
#endif//COMISO_QT_AVAILABLE
David Bommes's avatar
David Bommes committed
251
    }
David Bommes's avatar
David Bommes committed
252
253
254

    _problem->store_result(P(x));

255
    // ObjVal is only available if the optimize was called.
256
257
    DEB_out_if(solution_input_path_.empty(), 2,
        "GUROBI Objective: " << model.get(GRB_DoubleAttr_ObjVal) << "\n");
David Bommes's avatar
David Bommes committed
258
259
    return true;
  }
Jan Möbius's avatar
Jan Möbius committed
260
  catch(GRBException& e)
David Bommes's avatar
David Bommes committed
261
  {
262
    //process_gurobi_exception(e);
David Bommes's avatar
David Bommes committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    std::cout << "Error code = " << e.getErrorCode() << std::endl;
    std::cout << e.getMessage() << std::endl;
    return false;
  }
  catch(...)
  {
    std::cout << "Exception during optimization" << std::endl;
    return false;
  }

  return false;
}


David Bommes's avatar
David Bommes committed
277
278
//-----------------------------------------------------------------------------

Marcel Campen's avatar
Marcel Campen committed
279
280
281
bool
GUROBISolver::
solve_two_phase(NProblemInterface*                  _problem,                // problem instance
282
283
            const std::vector<NConstraintInterface*>& _constraints,            // linear constraints
            const std::vector<PairIndexVtype>&        _discrete_constraints,   // discrete constraints
Marcel Campen's avatar
Marcel Campen committed
284
285
286
287
288
289
290
291
292
            const double                        _time_limit0, // time limit phase 1 in seconds
            const double                        _gap0,     // MIP gap phase 1
            const double                        _time_limit1, // time limit phase 2 in seconds
            const double                        _gap1)       // MIP gap phase 2
{
  double dummy;
  return solve_two_phase(_problem, _constraints, _discrete_constraints, _time_limit0, _gap0, _time_limit1, _gap1, dummy);
}

David Bommes's avatar
David Bommes committed
293

294
295
296
bool
GUROBISolver::
solve_two_phase(NProblemInterface*                  _problem,                // problem instance
297
298
           const std::vector<NConstraintInterface *> &_constraints,            // linear constraints
           const std::vector<PairIndexVtype> &_discrete_constraints,   // discrete constraints
299
300
301
           const double                        _time_limit0, // time limit phase 1 in seconds
           const double                        _gap0,     // MIP gap phase 1
           const double                        _time_limit1, // time limit phase 2 in seconds
Marcel Campen's avatar
Marcel Campen committed
302
303
           const double                        _gap1,       // MIP gap phase 2
           double&                             _final_gap)  //return final gap
304
{
Max Lyon's avatar
Max Lyon committed
305
306
  DEB_enter_func;

307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
  try
  {
    //----------------------------------------------
    // 0. set up environment
    //----------------------------------------------

    GRBEnv   env   = GRBEnv();
    GRBModel model = GRBModel(env);


    //----------------------------------------------
    // 1. allocate variables
    //----------------------------------------------

    // determine variable types: 0->real, 1->integer, 2->bool
    std::vector<char> vtypes(_problem->n_unknowns(),0);
    for(unsigned int i=0; i<_discrete_constraints.size(); ++i)
      switch(_discrete_constraints[i].second)
      {
        case Integer: vtypes[_discrete_constraints[i].first] = 1; break;
        case Binary : vtypes[_discrete_constraints[i].first] = 2; break;
        default     : break;
      }

    // GUROBI variables
    std::vector<GRBVar> vars;
    // first all
    for( int i=0; i<_problem->n_unknowns(); ++i)
      switch(vtypes[i])
      {
        case 0 : vars.push_back( model.addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_CONTINUOUS) ); break;
        case 1 : vars.push_back( model.addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_INTEGER   ) ); break;
        case 2 : vars.push_back( model.addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_BINARY    ) ); break;
      }


    // Integrate new variables
    model.update();

    //----------------------------------------------
    // 2. setup constraints
    //----------------------------------------------

    // get zero vector
    std::vector<double> x(_problem->n_unknowns(), 0.0);

    for(unsigned int i=0; i<_constraints.size();  ++i)
    {
      if(!_constraints[i]->is_linear())
        std::cerr << "Warning: GUROBISolver received a problem with non-linear constraints!!!" << std::endl;

      GRBLinExpr lin_expr;
      NConstraintInterface::SVectorNC gc;
      _constraints[i]->eval_gradient(P(x), gc);

      NConstraintInterface::SVectorNC::InnerIterator v_it(gc);
      for(; v_it; ++v_it)
//        lin_expr += v_it.value()*vars[v_it.index()];
        lin_expr += vars[v_it.index()]*v_it.value();

      double b = _constraints[i]->eval_constraint(P(x));

      switch(_constraints[i]->constraint_type())
      {
        case NConstraintInterface::NC_EQUAL         : model.addConstr(lin_expr + b == 0); break;
        case NConstraintInterface::NC_LESS_EQUAL    : model.addConstr(lin_expr + b <= 0); break;
        case NConstraintInterface::NC_GREATER_EQUAL : model.addConstr(lin_expr + b >= 0); break;
      }
    }
    model.update();

    //----------------------------------------------
    // 3. setup energy
    //----------------------------------------------

    if(!_problem->constant_hessian())
      std::cerr << "Warning: GUROBISolver received a problem with non-constant hessian!!!" << std::endl;

    GRBQuadExpr objective;

    // add quadratic part
    NProblemInterface::SMatrixNP H;
    _problem->eval_hessian(P(x), H);
    for( int i=0; i<H.outerSize(); ++i)
      for (NProblemInterface::SMatrixNP::InnerIterator it(H,i); it; ++it)
        objective += 0.5*it.value()*vars[it.row()]*vars[it.col()];


    // add linear part
    std::vector<double> g(_problem->n_unknowns());
    _problem->eval_gradient(P(x), P(g));
    for(unsigned int i=0; i<g.size(); ++i)
      objective += g[i]*vars[i];

    // add constant part
    objective += _problem->eval_f(P(x));

    model.set(GRB_IntAttr_ModelSense, 1);
    model.setObjective(objective);
    model.update();


    //----------------------------------------------
    // 4. solve problem
    //----------------------------------------------


    if (solution_input_path_.empty())
    {
      if (!problem_env_output_path_.empty())
      {
        std::cout << "Writing problem's environment into file \"" << problem_env_output_path_ << "\"." << std::endl;
        model.getEnv().writeParams(problem_env_output_path_);
      }
421
#if (COMISO_QT_AVAILABLE)
422
423
424
425
426
      if (!problem_output_path_.empty())
      {
        std::cout << "Writing problem into file \"" << problem_output_path_ << "\"." << std::endl;
        GurobiHelper::outputModelToMpsGz(model, problem_output_path_);
      }
427
#endif//COMISO_QT_AVAILABLE
428
429
430
431
432

      // optimize
      model.getEnv().set(GRB_DoubleParam_TimeLimit, _time_limit0);
      model.getEnv().set(GRB_DoubleParam_MIPGap, _gap0);
      model.optimize();
Marcel Campen's avatar
Marcel Campen committed
433
      _final_gap = model.get(GRB_DoubleAttr_MIPGap);
434
435

      // jump into phase 2?
Marcel Campen's avatar
Marcel Campen committed
436
      if(model.get(GRB_DoubleAttr_MIPGap) > _gap1 && _time_limit1 > 0)
437
438
439
440
      {
        model.getEnv().set(GRB_DoubleParam_TimeLimit, _time_limit1);
        model.getEnv().set(GRB_DoubleParam_MIPGap, _gap1);
        model.optimize();
Marcel Campen's avatar
Marcel Campen committed
441
        _final_gap = model.get(GRB_DoubleAttr_MIPGap);
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
      }
    }
    else
    {
        std::cout << "Reading solution from file \"" << solution_input_path_ << "\"." << std::endl;
    }

    //----------------------------------------------
    // 5. store result
    //----------------------------------------------

    if (solution_input_path_.empty())
    {
      // store computed result
      for(unsigned int i=0; i<vars.size(); ++i)
        x[i] = vars[i].get(GRB_DoubleAttr_X);
    }
    else
    {
461
#if (COMISO_QT_AVAILABLE)
462
463
464
465
466
467
468
469
470
        std::cout << "Loading stored solution from \"" << solution_input_path_ << "\"." << std::endl;
        // store loaded result
        const size_t oldSize = x.size();
        x.clear();
        GurobiHelper::readSolutionVectorFromSOL(x, solution_input_path_);
        if (oldSize != x.size()) {
            std::cerr << "oldSize != x.size() <=> " << oldSize << " != " << x.size() << std::endl;
            throw std::runtime_error("Loaded solution vector doesn't have expected dimension.");
        }
471
#endif//COMISO_QT_AVAILABLE
472
473
474
475
476
    }

    _problem->store_result(P(x));

    // ObjVal is only available if the optimize was called.
477
478
    DEB_line_if(solution_input_path_.empty(), 2, 
      "GUROBI Objective: " << model.get(GRB_DoubleAttr_ObjVal));
479
480
481
482
    return true;
  }
  catch(GRBException& e)
  {
483
    //process_gurobi_exception(e);
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
    std::cout << "Error code = " << e.getErrorCode() << std::endl;
    std::cout << e.getMessage() << std::endl;
    return false;
  }
  catch(...)
  {
    std::cout << "Exception during optimization" << std::endl;
    return false;
  }

  return false;
}


//-----------------------------------------------------------------------------


bool
GUROBISolver::
solve(NProblemInterface*                        _problem,
      const std::vector<NConstraintInterface*>& _constraints,
      const std::vector<NConstraintInterface*>& _lazy_constraints,
      std::vector<PairIndexVtype>&              _discrete_constraints,   // discrete constraints
      const double                              _almost_infeasible,
      const int                                 _max_passes,
      const double                              _time_limit,
      const bool                                _silent)
{
512
  DEB_time_func_def;
513
514
515
516
517
518
519
//  // hack! solve with all constraints
//  std::vector<NConstraintInterface*> all_constraints;
//  std::copy(_constraints.begin(),_constraints.end(),std::back_inserter(all_constraints));
//  std::copy(_lazy_constraints.begin(),_lazy_constraints.end(),std::back_inserter(all_constraints));
//
//  return solve(_problem, all_constraints, _discrete_constraints, _time_limit);

Max Lyon's avatar
Max Lyon committed
520
521
  StopWatch sw; sw.start();

522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
  bool feasible_point_found = false;
  int  cur_pass = 0;
  double acceptable_tolerance = 0.01; // hack: read out from ipopt!!!
  std::vector<bool> lazy_added(_lazy_constraints.size(),false);

  // cache statistics of all iterations
  std::vector<int> n_inf;
  std::vector<int> n_almost_inf;

  try
  {
    //----------------------------------------------
    // 0. set up environment
    //----------------------------------------------

    GRBEnv   env   = GRBEnv();
    GRBModel model = GRBModel(env);

    model.getEnv().set(GRB_DoubleParam_TimeLimit, _time_limit);


    //----------------------------------------------
    // 1. allocate variables
    //----------------------------------------------

    // determine variable types: 0->real, 1->integer, 2->bool
    std::vector<char> vtypes(_problem->n_unknowns(),0);
    for(unsigned int i=0; i<_discrete_constraints.size(); ++i)
      switch(_discrete_constraints[i].second)
      {
        case Integer: vtypes[_discrete_constraints[i].first] = 1; break;
        case Binary : vtypes[_discrete_constraints[i].first] = 2; break;
        default     : break;
      }

    // GUROBI variables
    std::vector<GRBVar> vars;
    // first all
    for( int i=0; i<_problem->n_unknowns(); ++i)
      switch(vtypes[i])
      {
        case 0 : vars.push_back( model.addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_CONTINUOUS) ); break;
        case 1 : vars.push_back( model.addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_INTEGER   ) ); break;
        case 2 : vars.push_back( model.addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_BINARY    ) ); break;
      }


    // Integrate new variables
    model.update();

    //----------------------------------------------
    // 2. setup constraints
    //----------------------------------------------

    // get zero vector
    std::vector<double> x(_problem->n_unknowns(), 0.0);

    for(unsigned int i=0; i<_constraints.size();  ++i)
    {
      add_constraint_to_model(_constraints[i], model, vars, P(x));
    }
    model.update();

    //----------------------------------------------
    // 3. setup energy
    //----------------------------------------------

589
590
    DEB_warning_if(!_problem->constant_hessian(), 1,
      "GUROBISolver received a problem with non-constant hessian!!!\n");
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701

    GRBQuadExpr objective;

    // add quadratic part
    NProblemInterface::SMatrixNP H;
    _problem->eval_hessian(P(x), H);
    for( int i=0; i<H.outerSize(); ++i)
      for (NProblemInterface::SMatrixNP::InnerIterator it(H,i); it; ++it)
        objective += 0.5*it.value()*vars[it.row()]*vars[it.col()];


    // add linear part
    std::vector<double> g(_problem->n_unknowns());
    _problem->eval_gradient(P(x), P(g));
    for(unsigned int i=0; i<g.size(); ++i)
      objective += g[i]*vars[i];

    // add constant part
    objective += _problem->eval_f(P(x));

    model.set(GRB_IntAttr_ModelSense, 1);
    model.setObjective(objective);


    //----------------------------------------------
    // 4. iteratively solve problem
    //----------------------------------------------
    bool solution_found = false;

    while(!feasible_point_found && cur_pass <(_max_passes-1))
    {
      ++cur_pass;
      //----------------------------------------------------------------------------
      // 1. optimize current Model and get result
      //----------------------------------------------------------------------------

      model.update();
      model.optimize();
      // store computed result
      if(model.get(GRB_IntAttr_Status) == GRB_OPTIMAL)
        for(unsigned int i=0; i<vars.size(); ++i)
          x[i] = vars[i].get(GRB_DoubleAttr_X);

      //----------------------------------------------------------------------------
      // 2. Check lazy constraints
      //----------------------------------------------------------------------------
      // check lazy constraints
      n_inf.push_back(0);
      n_almost_inf.push_back(0);
      feasible_point_found = true;
      for(unsigned int i=0; i<_lazy_constraints.size(); ++i)
        if(!lazy_added[i])
        {
          NConstraintInterface* lc = _lazy_constraints[i];

          double v = lc->eval_constraint(P(x));

          bool inf        = false;
          bool almost_inf = false;

          if(lc->constraint_type() == NConstraintInterface::NC_EQUAL)
          {
            v = std::abs(v);
            if(v>acceptable_tolerance)
              inf = true;
            else
              if(v>_almost_infeasible)
                almost_inf = true;
          }
          else
            if(lc->constraint_type() == NConstraintInterface::NC_GREATER_EQUAL)
            {
              if(v<-acceptable_tolerance)
                inf = true;
              else
                if(v<_almost_infeasible)
                  almost_inf = true;
            }
            else
              if(lc->constraint_type() == NConstraintInterface::NC_LESS_EQUAL)
              {
                if(v>acceptable_tolerance)
                  inf = true;
                else
                  if(v>-_almost_infeasible)
                    almost_inf = true;
              }

          // infeasible?
              if(inf)
              {
                add_constraint_to_model( lc, model, vars, P(x));
                lazy_added[i] = true;
                feasible_point_found = false;
                ++n_inf.back();
              }
              else // almost violated or violated? -> add to constraints
                if(almost_inf)
                {
                  add_constraint_to_model( lc, model, vars, P(x));
                  lazy_added[i] = true;
                  ++n_almost_inf.back();
                }
        }
    }

    // no termination after max number of passes?
    if(!feasible_point_found)
    {
      ++cur_pass;

702
703
      DEB_out(1, "*************** could not find feasible point after " 
        << _max_passes-1 << " -> solving with all lazy constraints...\n");
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
      for(unsigned int i=0; i<_lazy_constraints.size(); ++i)
        if(!lazy_added[i])
        {
          add_constraint_to_model( _lazy_constraints[i], model, vars, P(x));
        }

      model.update();
      model.optimize();

      // store computed result
      if(model.get(GRB_IntAttr_Status) == GRB_OPTIMAL)
        for(unsigned int i=0; i<vars.size(); ++i)
          x[i] = vars[i].get(GRB_DoubleAttr_X);
    }

    const double overall_time = sw.stop()/1000.0;

    //----------------------------------------------------------------------------
    // 4. output statistics
    //----------------------------------------------------------------------------
724
725
726
727
    // Make this code DEB_only
    DEB_line(2,
      "############# GUROBI with lazy constraints statistics ###############");
    DEB_line(2, "#passes     : " << cur_pass << "( of " << _max_passes << ")");
728
    for(unsigned int i=0; i<n_inf.size(); ++i)
729
730
731
732
733
    {
      DEB_line(2, "pass " << i << " induced " << n_inf[i]
        << " infeasible and " << n_almost_inf[i] << " almost infeasible");
    }
    DEB_line(2, "GUROBI Objective: " << model.get(GRB_DoubleAttr_ObjVal));
734
735
736
737

    //----------------------------------------------
    // 5. store result
    //----------------------------------------------
738
739
740
    //COMISO_THROW_TODO_if(model.get(GRB_IntAttr_Status) != GRB_OPTIMAL, 
    //  "Gurobi solution not optimal");

741
742
743
744
745
746
747
748
749
750
    if(model.get(GRB_IntAttr_Status) != GRB_OPTIMAL)
      return false;
    else
    {
      _problem->store_result(P(x));
      return true;
    }
  }
  catch(GRBException& e)
  {
751
752
    //process_gurobi_exception(e);

753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
    std::cout << "Error code = " << e.getErrorCode() << std::endl;
    std::cout << e.getMessage() << std::endl;
    return false;
  }
  catch(...)
  {
    std::cout << "Exception during optimization" << std::endl;
    return false;
  }

  return false;

//    //----------------------------------------------
//    // 4. iteratively solve problem
//    //----------------------------------------------
//    IloBool solution_found = IloFalse;
//
//    while(!feasible_point_found && cur_pass <(_max_passes-1))
//    {
//      ++cur_pass;
//      //----------------------------------------------------------------------------
//      // 1. Create an instance of current Model and optimize
//      //----------------------------------------------------------------------------
//
//      if(!_silent)
//        std::cerr << "cplex -> setup IloCPlex...\n";
//      IloCplex cplex(model);
//      cplex.setParam(IloCplex::TiLim, _time_limit);
//      // silent mode?
//      if(_silent)
//        cplex.setOut(env_.getNullStream());
//
//      if(!_silent)
//        std::cerr << "cplex -> optimize...\n";
//      solution_found = cplex.solve();
//
//      if(solution_found != IloFalse)
//      {
//        for(unsigned int i=0; i<vars.size(); ++i)
//          x[i] = cplex.getValue(vars[i]);
//
//        _problem->store_result(P(x));
//      }
//      else continue;
//
//      //----------------------------------------------------------------------------
//      // 2. Check lazy constraints
//      //----------------------------------------------------------------------------
//      // check lazy constraints
//      n_inf.push_back(0);
//      n_almost_inf.push_back(0);
//      feasible_point_found = true;
//      for(unsigned int i=0; i<_lazy_constraints.size(); ++i)
//        if(!lazy_added[i])
//        {
//          NConstraintInterface* lc = _lazy_constraints[i];
//
//          double v = lc->eval_constraint(P(x));
//
//          bool inf        = false;
//          bool almost_inf = false;
//
//          if(lc->constraint_type() == NConstraintInterface::NC_EQUAL)
//          {
//            v = std::abs(v);
//            if(v>acceptable_tolerance)
//              inf = true;
//            else
//              if(v>_almost_infeasible)
//                almost_inf = true;
//          }
//          else
//            if(lc->constraint_type() == NConstraintInterface::NC_GREATER_EQUAL)
//            {
//              if(v<-acceptable_tolerance)
//                inf = true;
//              else
//                if(v<_almost_infeasible)
//                  almost_inf = true;
//            }
//            else
//              if(lc->constraint_type() == NConstraintInterface::NC_LESS_EQUAL)
//              {
//                if(v>acceptable_tolerance)
//                  inf = true;
//                else
//                  if(v>-_almost_infeasible)
//                    almost_inf = true;
//              }
//
//          // infeasible?
//          if(inf)
//          {
//            add_constraint_to_model( lc, vars, model, env_, P(x));
//            lazy_added[i] = true;
//            feasible_point_found = false;
//            ++n_inf.back();
//          }
//          else // almost violated or violated? -> add to constraints
//            if(almost_inf)
//            {
//              add_constraint_to_model( lc, vars, model, env_, P(x));
//              lazy_added[i] = true;
//              ++n_almost_inf.back();
//            }
//        }
//    }
//
//    // no termination after max number of passes?
//    if(!feasible_point_found)
//    {
//      ++cur_pass;
//
//      std::cerr << "*************** could not find feasible point after " << _max_passes-1 << " -> solving with all lazy constraints..." << std::endl;
//      for(unsigned int i=0; i<_lazy_constraints.size(); ++i)
//        if(!lazy_added[i])
//        {
//          add_constraint_to_model( _lazy_constraints[i], vars, model, env_, P(x));
//        }
//
//      //----------------------------------------------------------------------------
//      // 1. Create an instance of current Model and optimize
//      //----------------------------------------------------------------------------
//
//      IloCplex cplex(model);
//      cplex.setParam(IloCplex::TiLim, _time_limit);
//      // silent mode?
//      if(_silent)
//        cplex.setOut(env_.getNullStream());
//      solution_found = cplex.solve();
//
//      if(solution_found != IloFalse)
//      {
//        for(unsigned int i=0; i<vars.size(); ++i)
//          x[i] = cplex.getValue(vars[i]);
//
//        _problem->store_result(P(x));
//      }
//    }
//
//    const double overall_time = sw.stop()/1000.0;
//
//    //----------------------------------------------------------------------------
//    // 4. output statistics
//    //----------------------------------------------------------------------------
////    if (solution_found != IloFalse)
////    {
////      // Retrieve some statistics about the solve
////      Ipopt::Index iter_count = app_->Statistics()->IterationCount();
////      printf("\n\n*** IPOPT: The problem solved in %d iterations!\n", iter_count);
////
////      Ipopt::Number final_obj = app_->Statistics()->FinalObjective();
////      printf("\n\n*** IPOPT: The final value of the objective function is %e.\n", final_obj);
////    }
//
//    std::cerr <<"############# CPLEX with lazy constraints statistics ###############" << std::endl;
//    std::cerr << "overall time: " << overall_time << "s" << std::endl;
//    std::cerr << "#passes     : " << cur_pass << "( of " << _max_passes << ")" << std::endl;
//    for(unsigned int i=0; i<n_inf.size(); ++i)
//      std::cerr << "pass " << i << " induced " << n_inf[i] << " infeasible and " << n_almost_inf[i] << " almost infeasible" << std::endl;
//
//    return (solution_found != IloFalse);
}


//-----------------------------------------------------------------------------


David Bommes's avatar
David Bommes committed
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
void
GUROBISolver::
set_problem_output_path( const std::string &_problem_output_path)
{
  problem_output_path_ = _problem_output_path;
}


//-----------------------------------------------------------------------------


void
GUROBISolver::
set_problem_env_output_path( const std::string &_problem_env_output_path)
{
  problem_env_output_path_ = _problem_env_output_path;
}


//-----------------------------------------------------------------------------


void
GUROBISolver::
set_solution_input_path(const std::string &_solution_input_path)
{
  solution_input_path_ = _solution_input_path;
}


David Bommes's avatar
David Bommes committed
951
952
953
954
955
//=============================================================================
} // namespace COMISO
//=============================================================================
#endif // COMISO_GUROBI_AVAILABLE
//=============================================================================