MISolver.cc 22.5 KB
Newer Older
Henrik Zimmer's avatar
Henrik Zimmer committed
1
2
/*===========================================================================*\
 *                                                                           *
Henrik Zimmer's avatar
Henrik Zimmer committed
3
 *                               CoMISo                                      *
Henrik Zimmer's avatar
Henrik Zimmer committed
4
 *      Copyright (C) 2008-2009 by Computer Graphics Group, RWTH Aachen      *
Henrik Zimmer's avatar
Henrik Zimmer committed
5
 *                           www.rwth-graphics.de                            *
Henrik Zimmer's avatar
Henrik Zimmer committed
6
 *                                                                           *
Henrik Zimmer's avatar
Henrik Zimmer committed
7
8
 *---------------------------------------------------------------------------* 
 *  This file is part of CoMISo.                                             *
Henrik Zimmer's avatar
Henrik Zimmer committed
9
 *                                                                           *
Henrik Zimmer's avatar
Henrik Zimmer committed
10
11
12
13
 *  CoMISo is free software: you can redistribute it and/or modify           *
 *  it under the terms of the GNU General Public License as published by     *
 *  the Free Software Foundation, either version 3 of the License, or        *
 *  (at your option) any later version.                                      *
Henrik Zimmer's avatar
Henrik Zimmer committed
14
15
16
17
 *                                                                           *
 *  CoMISo is distributed in the hope that it will be useful,                *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
Henrik Zimmer's avatar
Henrik Zimmer committed
18
 *  GNU General Public License for more details.                             *
Henrik Zimmer's avatar
Henrik Zimmer committed
19
 *                                                                           *
Henrik Zimmer's avatar
Henrik Zimmer committed
20
21
 *  You should have received a copy of the GNU General Public License        *
 *  along with CoMISo.  If not, see <http://www.gnu.org/licenses/>.          *
Henrik Zimmer's avatar
Henrik Zimmer committed
22
 *                                                                           *
Henrik Zimmer's avatar
Henrik Zimmer committed
23
\*===========================================================================*/ 
Henrik Zimmer's avatar
Henrik Zimmer committed
24
25


David Bommes's avatar
David Bommes committed
26
#include <CoMISo/Config/config.hh>
27
#include "MISolver.hh"
28
#include "CoMISo/Utils/CoMISoError.hh"
29

30
#if(COMISO_QT_AVAILABLE)
31
#include <CoMISo/QtWidgets/MISolverDialogUI.hh>
32
33
#endif

David Bommes's avatar
David Bommes committed
34
35
36
37
#if COMISO_GUROBI_AVAILABLE
  #include <gurobi_c++.h>
#endif

38
39
#include <Base/Debug/DebOut.hh>
#include <Base/Utils/StopWatch.hh>
David Bommes's avatar
David Bommes committed
40

41
42
43
#include <gmm/gmm.h>
#include <float.h>

44
45
46
// hack for testing only
#include "SparseQRSolver.hh"
#include "UMFPACKSolver.hh"
47
#include "EigenLDLTSolver.hh"
David Bommes's avatar
David Bommes committed
48

49
50
#define ROUND(x) ((x)<0?int((x)-0.5):int((x)+0.5))

51
namespace COMISO {
52
53
54
55
56
57
58
59



// Constructor
MISolver::MISolver() 
{
  // default parameters
  initial_full_solution_ = true;
David Bommes's avatar
David Bommes committed
60
  iter_full_solution_    = true;
61
62
  final_full_solution_   = true;

David Bommes's avatar
David Bommes committed
63
64
65
  direct_rounding_   = false;
  no_rounding_       = false;
  multiple_rounding_ = true;
David Bommes's avatar
David Bommes committed
66
  gurobi_rounding_   = false;
David Bommes's avatar
David Bommes committed
67
  cplex_rounding_    = false;
68

David Bommes's avatar
David Bommes committed
69
  max_local_iters_ = 100000;
70
  max_local_error_ = 1e-3;
David Bommes's avatar
David Bommes committed
71
  max_cg_iters_    = 50;
72
  max_cg_error_    = 1e-3;
David Bommes's avatar
David Bommes committed
73
74
75

  multiple_rounding_threshold_ = 0.5;

David Bommes's avatar
David Bommes committed
76
77
  gurobi_max_time_ = 60;

78
79
  noisy_ = 0;
  stats_ = true;
80
81

  use_constraint_reordering_ = true;
82
83
}

David Bommes's avatar
David Bommes committed
84

85
86
87
88
89
90
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
//-----------------------------------------------------------------------------

void
MISolver::solve(
    CSCMatrix& _A,
    Vecd&      _x,
    Vecd&      _rhs,
    Veci&      _to_round,
    bool       _fixed_order )
{
  DEB_enter_func

  DEB_out(2, "# integer    variables: " << _to_round.size() 
    << "\n# continuous variables: " << _x.size()-_to_round.size() << "\n")

        // nothing to solve?
        if( gmm::mat_ncols(_A) == 0 || gmm::mat_nrows(_A) == 0)
                return;

        if( gurobi_rounding_)
                solve_gurobi(_A, _x, _rhs, _to_round);
        else if( cplex_rounding_)
                solve_cplex(_A, _x, _rhs, _to_round);
        else if( no_rounding_ || _to_round.size() == 0)
                solve_no_rounding( _A, _x, _rhs);
        else if( direct_rounding_)
                solve_direct_rounding( _A, _x, _rhs, _to_round);
        else if( multiple_rounding_)
                solve_multiple_rounding( _A, _x, _rhs, _to_round);
        else
                solve_iterative( _A, _x, _rhs, _to_round, _fixed_order);
}


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

// inline function...
void
MISolver::solve_cplex(
    CSCMatrix& _A,
    Vecd&      _x,
    Vecd&      _rhs,
    Veci&      _to_round)
{
  DEB_enter_func;
        DEB_out(2, "gurobi_max_time_: " << gurobi_max_time_ << "\n")

#if COMISO_CPLEX_AVAILABLE

  // get round-indices in set
  std::set<int> to_round;
  for(unsigned int i=0; i<_to_round.size();++i)
    to_round.insert(_to_round[i]);

  try {

    IloEnv env_;
    IloModel model(env_);

    // set time limite
    //    model.getEnv().set(GRB_DoubleParam_TimeLimit, gurobi_max_time_);

    unsigned int n = _rhs.size();

    // 1. allocate variables
    std::vector<IloNumVar> vars;
    for( unsigned int i=0; i<n; ++i)
      if( to_round.count(i))
        vars.push_back( IloNumVar(env_,  -IloIntMax,   IloIntMax, IloNumVar::Int)   );
      else
        vars.push_back( IloNumVar(env_,-IloInfinity, IloInfinity, IloNumVar::Float) );


    // 2. setup_energy

    // build objective function from linear system E = x^tAx - 2x^t*rhs
    IloExpr objective(env_);

    for(unsigned int i=0; i<_A.nc; ++i)
      for(unsigned int j=_A.jc[i]; j<_A.jc[i+1]; ++j)
      {
        objective += _A.pr[j]*vars[_A.ir[j]]*vars[i];
      }
    for(unsigned int i=0; i<n; ++i)
      objective -= 2*_rhs[i]*vars[i];

    // ToDo: objective correction!!!

    //    _A.jc[c+1]
    //    _A.pr[write]
    //    _A.ir[write]
    //    _A.nc
    //    _A.nr

    // minimize
    model.add(IloMinimize(env_,objective));

    // 4. solve
    IloCplex cplex(model);
    cplex.setParam(IloCplex::TiLim, gurobi_max_time_);

//    // set parameters comparable to CoMISo
//    {
//      cplex.setParam(IloCplex::MIPSearch  , 1);  // Traditional Branch-and-Cut
//      cplex.setParam(IloCplex::NodeSel    , 0);  // Depth-First
//      cplex.setParam(IloCplex::VarSel     , -1);  // closest to integer
//      cplex.setParam(IloCplex::MIPEmphasis, 1);  // concentrate on feasibility
//    }

    cplex.solve();

    // 5. store result
    _x.resize(n);
    for(unsigned int i=0; i<n; ++i)
      _x[i] = cplex.getValue(vars[i]);

    DEB_out(2, "CPLEX objective: " << cplex.getObjValue() <<"\n");

  }
  catch (IloException& e)
  {
206
    DEB_warning(2, "CPLEX Concert exception caught: " << e.getMessage() )
207
208
209
210
211
212
213
214
215
216
217
218
  }
  catch (...)
  {
    DEB_warning(1, "CPLEX Unknown exception caught" )
  }


#else
  DEB_out(1, "CPLEX solver is not available, please install it...\n")
#endif
}

219
220
221
//-----------------------------------------------------------------------------


David Bommes's avatar
David Bommes committed
222
223
224
225
226
227
void 
MISolver::solve_no_rounding( 
    CSCMatrix& _A, 
    Vecd&      _x, 
    Vecd&      _rhs )
{
228
229
  COMISO_THROW_if(!direct_solver_.calc_system_gmm(_A), UNSPECIFIED_EIGEN_FAILURE);
  COMISO_THROW_if(!direct_solver_.solve(_x, _rhs), UNSPECIFIED_EIGEN_FAILURE);
David Bommes's avatar
David Bommes committed
230
231
232
233
234
235
236
}


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


void 
237
238
239
240
MISolver::resolve(
    Vecd&      _x,
    Vecd&      _rhs )
{
241
  direct_solver_.solve(_x, _rhs);
242
243
244
245
246
247
248
}


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


void
David Bommes's avatar
David Bommes committed
249
250
251
252
253
254
MISolver::solve_direct_rounding( 
    CSCMatrix& _A, 
    Vecd&      _x, 
    Vecd&      _rhs, 
    Veci&      _to_round)
{
255
  DEB_enter_func
David Bommes's avatar
David Bommes committed
256
257
258
259
260
  Veci to_round(_to_round);
  // copy to round vector and make it unique
  std::sort(to_round.begin(), to_round.end());
  Veci::iterator last_unique;
  last_unique = std::unique(to_round.begin(), to_round.end());
Max Lyon's avatar
Max Lyon committed
261
  size_t r = (size_t)(last_unique - to_round.begin());
David Bommes's avatar
David Bommes committed
262
263
264
265
266
267
  to_round.resize( r);

  // initalize old indices
  Veci old_idx(_rhs.size());
  for(unsigned int i=0; i<old_idx.size(); ++i)
    old_idx[i] = i;
268
269
  direct_solver_.calc_system_gmm(_A);
  direct_solver_.solve(_x, _rhs);
David Bommes's avatar
David Bommes committed
270

271
272
  // check solver performance (only for testing!!!)
  {
273
    Base::StopWatch sw;
274

275
    // hack
David Bommes's avatar
David Bommes committed
276
277
    const bool enable_performance_test = false;

278
    // performance comparison code
David Bommes's avatar
changed    
David Bommes committed
279
#if(COMISO_SUITESPARSE_SPQR_AVAILABLE)
David Bommes's avatar
David Bommes committed
280
    if(enable_performance_test)
281
282
283
284
285
286
287
288
289
290
291
292
293
    {
      sw.start();
      COMISO::SparseQRSolver spqr;
      spqr.calc_system_gmm(_A);
      std::cerr << "SparseQR factor took: " << sw.stop()/1000.0 << "s\n";
      Vecd x2(_x);
      sw.start();
      spqr.solve(x2,_rhs);
      std::cerr << "SparseQR solve took: " << sw.stop()/1000.0 << "s\n";
      Vecd res(_x);
      gmm::add(_x,gmm::scaled(x2,-1.0),res);
      std::cerr << "DIFFERENCE IN RESULT: " << gmm::vect_norm2(res) << std::endl;
    }
David Bommes's avatar
changed    
David Bommes committed
294
#endif
295
296

    // performance comparison code
297
#if(COMISO_SUITESPARSE_AVAILABLE)
David Bommes's avatar
David Bommes committed
298
    if(enable_performance_test)
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    {
      sw.start();
      COMISO::UMFPACKSolver umf;
      umf.calc_system_gmm(_A);
      std::cerr << "UMFPack factor took: " << sw.stop()/1000.0 << "s\n";
      Vecd x3(_x);
      sw.start();
      umf.solve(x3,_rhs);
      std::cerr << "UMFPack solve took: " << sw.stop()/1000.0 << "s\n";
      Vecd res2(_x);
      gmm::add(_x,gmm::scaled(x3,-1.0),res2);
      std::cerr << "UMFPACK DIFFERENCE IN RESULT: " << gmm::vect_norm2(res2) << std::endl;
    }

    // performance comparison code
David Bommes's avatar
David Bommes committed
314
    if(enable_performance_test)
315
316
317
318
319
320
321
322
323
324
325
326
327
    {
      sw.start();
      COMISO::CholmodSolver chol;
      chol.calc_system_gmm(_A);
      std::cerr << "Choldmod factor took: " << sw.stop()/1000.0 << "s\n";
      Vecd x4(_x);
      sw.start();
      chol.solve(x4,_rhs);
      std::cerr << "Choldmod solve took: " << sw.stop()/1000.0 << "s\n";
      Vecd res(_x);
      gmm::add(_x,gmm::scaled(x4,-1.0),res);
      std::cerr << "DIFFERENCE IN RESULT: " << gmm::vect_norm2(res) << std::endl;
    }
328
329
#endif

David Bommes's avatar
David Bommes committed
330
#if(COMISO_EIGEN3_AVAILABLE)
331
332
333
334
335
336
    // performance comparison code
    if(enable_performance_test)
    {
      sw.start();
      COMISO::EigenLDLTSolver ldlt;
      ldlt.calc_system_gmm(_A);
337
      DEB_out(2, "Eigen LDLT factor took: " << sw.stop()/1000.0 << "s\n")
338
339
340
      Vecd x5(_x);
      sw.start();
      ldlt.solve(x5,_rhs);
341
      DEB_out(2, "Eigen LDLT solve took: " << sw.stop()/1000.0 << "s\n")
342
343
      Vecd res(_x);
      gmm::add(_x,gmm::scaled(x5,-1.0),res);
344
      DEB_warning(2, "DIFFERENCE IN RESULT: " << gmm::vect_norm2(res) )
345
346
    }
#endif
347
  }
David Bommes's avatar
David Bommes committed
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

  // round and eliminate variables
  Vecui elim_i;
  Vecd  elim_v;
  for( unsigned int i=0; i < to_round.size(); ++i)
  {
    _x[to_round[i]] = ROUND(_x[to_round[i]]);
    elim_i.push_back(to_round[i]);
    elim_v.push_back(_x[to_round[i]]);
    // update old idx
    old_idx[to_round[i]] = -1;
  }

  Veci::iterator new_end = std::remove( old_idx.begin(), old_idx.end(), -1);
  old_idx.resize( new_end-old_idx.begin());
  // eliminate vars from linear system
  Vecd xr(_x);
  COMISO_GMM::eliminate_csc_vars2( elim_i, elim_v, _A, xr, _rhs);

  // std::cerr << "size A: " << gmm::mat_nrows(_A) << " " << gmm::mat_ncols(_A) 
  // 	    << std::endl;
  // std::cerr << "size x  : " << xr.size() << std::endl;
  // std::cerr << "size rhs: " << _rhs.size() << std::endl;

  // final full solution
  if( gmm::mat_ncols( _A) > 0)
  {
375
376
377
    //    direct_solver_.update_system_gmm(_A);
    direct_solver_.calc_system_gmm(_A);
    direct_solver_.solve( xr, _rhs);
David Bommes's avatar
David Bommes committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
  }

  // store solution values to result vector
  for(unsigned int i=0; i<old_idx.size(); ++i)
  {
    _x[ old_idx[i] ] = xr[i];
  }
}


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


void 
MISolver::solve_iterative( 
    CSCMatrix& _A, 
    Vecd&      _x, 
    Vecd&      _rhs, 
    Veci&      _to_round,
    bool       _fixed_order )
{
399
  DEB_enter_func;
David Bommes's avatar
David Bommes committed
400
  // StopWatch
401
  Base::StopWatch sw;
David Bommes's avatar
David Bommes committed
402
403
  double time_search_next_integer = 0;

404
  // some statistics
David Bommes's avatar
David Bommes committed
405
406
407
408
409
410
  n_local_ = 0;
  n_cg_    = 0;
  n_full_  = 0;

  // reset cholmod step flag
  cholmod_step_done_ = false;
411
412
413
414
415
416
417
418
419

  Veci to_round(_to_round);
  // if the order is not fixed, uniquify the indices
  if( !_fixed_order)
  {
    // copy to round vector and make it unique
    std::sort(to_round.begin(), to_round.end());
    Veci::iterator last_unique;
    last_unique = std::unique(to_round.begin(), to_round.end());
Max Lyon's avatar
Max Lyon committed
420
    size_t r = (size_t)(last_unique - to_round.begin());
421
422
423
424
425
426
427
428
    to_round.resize( r);
  }

  // initalize old indices
  Veci old_idx(_rhs.size());
  for(unsigned int i=0; i<old_idx.size(); ++i)
    old_idx[i] = i;

David Bommes's avatar
David Bommes committed
429
  if( initial_full_solution_)
430
  {
431
    DEB_out_if( noisy_ > 2, 2,  "initial full solution\n")
432
433
    direct_solver_.calc_system_gmm(_A);
    direct_solver_.solve(_x, _rhs);
434

David Bommes's avatar
David Bommes committed
435
    cholmod_step_done_ = true;
436

David Bommes's avatar
David Bommes committed
437
438
    ++n_full_;
  }
439
440
441
442
443
444
445
446
447
448
449
450

  // neighbors for local optimization
  Vecui neigh_i;

  // Vector for reduced solution
  Vecd xr(_x);

  // loop until solution computed
  for(unsigned int i=0; i<to_round.size(); ++i)
  {
    if( noisy_ > 0)
    {
451
452
453
      DEB_out(2, "Integer DOF's left: " << to_round.size()-(i+1) << " ")
      DEB_out_if( noisy_ > 1, 1, "residuum_norm: "
        << COMISO_GMM::residuum_norm( _A, xr, _rhs) << "\n")
454
455
456
457
458
    }

    // index to eliminate
    unsigned int i_best = 0;

David Bommes's avatar
David Bommes committed
459
460
461
    // position in round vector
    unsigned int tr_best = 0;

462
463
464
465
466
467
    if( _fixed_order ) // if order is fixed, simply get next index from to_round
    {
      i_best = to_round[i];
    }
    else               // else search for best rounding candidate
    {
David Bommes's avatar
David Bommes committed
468
      sw.start();
469
470
471
472
473
474
475
476
477
478
      // find index yielding smallest rounding error
      double       r_best = FLT_MAX;
      for(unsigned int j=0; j<to_round.size(); ++j)
      {
        if( to_round[j] != -1)
        {
          int cur_idx = to_round[j];
          double rnd_error = fabs( ROUND(xr[cur_idx]) - xr[cur_idx]);
          if( rnd_error < r_best)
          {
David Bommes's avatar
David Bommes committed
479
480
481
            i_best  = cur_idx;
            r_best  = rnd_error;
	    tr_best = j;
482
483
484
          }
        }
      }
David Bommes's avatar
David Bommes committed
485
      time_search_next_integer += sw.stop();
486
487
488
489
490
491
492
493
494
495
496
497
    }

    // store rounded value
    double rnd_x = ROUND(xr[i_best]);
    _x[ old_idx[i_best] ] = rnd_x;

    // compute neighbors
    neigh_i.clear();
    Col col = gmm::mat_const_col(_A, i_best);
    ColIter it  = gmm::vect_const_begin( col);
    ColIter ite = gmm::vect_const_end  ( col);
    for(; it!=ite; ++it)
David Bommes's avatar
David Bommes committed
498
      if(it.index() != i_best)
Andreas Fabri's avatar
Andreas Fabri committed
499
        neigh_i.push_back(static_cast<int>(it.index()));
500
501

    // eliminate var
David Bommes's avatar
David Bommes committed
502
503
    COMISO_GMM::fix_var_csc_symmetric(i_best, rnd_x, _A, xr, _rhs);
    to_round[tr_best] = -1;
504

David Bommes's avatar
David Bommes committed
505
506
507
508
    // 3-stage update of solution w.r.t. roundings
    // local GS / CG / SparseCholesky
    update_solution( _A, xr, _rhs, neigh_i);
  }
509

David Bommes's avatar
David Bommes committed
510
511
512
  // final full solution?
  if( final_full_solution_)
  {
513
    DEB_out_if( noisy_ > 2, 2, "final full solution\n")
514

David Bommes's avatar
David Bommes committed
515
    if( gmm::mat_ncols( _A) > 0)
516
    {
David Bommes's avatar
David Bommes committed
517
      if(cholmod_step_done_)
518
	direct_solver_.update_system_gmm(_A);
David Bommes's avatar
David Bommes committed
519
      else
520
	direct_solver_.calc_system_gmm(_A);
521

522
      direct_solver_.solve( xr, _rhs);
David Bommes's avatar
David Bommes committed
523
      ++n_full_;
524
    }
David Bommes's avatar
David Bommes committed
525
526
527
528
529
530
531
532
533
  }

  // store solution values to result vector
  for(unsigned int i=0; i<old_idx.size(); ++i)
  {
    _x[ old_idx[i] ] = xr[i];
  }

  // output statistics
534
535
536
537
538
539
540
  DEB_out_if( stats_, 2, " *** Statistics of MiSo Solver ***"
    << "\n Number of CG    iterations  = " << n_cg_
    << "\n Number of LOCAL iterations  = " << n_local_
    << "\n Number of FULL  iterations  = " << n_full_
    << "\n Number of ROUNDING          = " << _to_round.size()
    << "\n time searching next integer = " 
    << time_search_next_integer / 1000.0 << "s\n\n")
David Bommes's avatar
David Bommes committed
541
}
542
543


David Bommes's avatar
David Bommes committed
544
545
546
547
548
549
550
551
552
553
//-----------------------------------------------------------------------------


void 
MISolver::update_solution( 
    CSCMatrix& _A, 
    Vecd&      _x, 
    Vecd&      _rhs, 
    Vecui&     _neigh_i )
{
554
  DEB_enter_func
David Bommes's avatar
David Bommes committed
555
556
557
558
559
560
  // set to not converged
  bool converged = false;

  // compute new solution
  if(max_local_iters_ > 0)
  {
561
    DEB_out_if( noisy_ > 2, 2, "use local iteration ")
David Bommes's avatar
David Bommes committed
562
563
564
565
566
567
568
569
570
571
572
573

    int    n_its     = max_local_iters_;
    double tolerance = max_local_error_;
    converged = siter_.gauss_seidel_local(_A, _x, _rhs, _neigh_i, n_its, tolerance);

    ++n_local_;
  }


  // conjugate gradient
  if( !converged && max_cg_iters_ > 0)
  {
574
    DEB_out_if( noisy_ > 2, 2, ", cg ")
David Bommes's avatar
David Bommes committed
575
576
577
578
579

    int max_cg_iters = max_cg_iters_;
    double tolerance = max_cg_error_;
    converged = siter_.conjugate_gradient(_A, _x,_rhs, max_cg_iters, tolerance);

580
    DEB_out_if( noisy_ > 3, 3,  "( converged " << converged << " "
David Bommes's avatar
David Bommes committed
581
		<< " iters " << max_cg_iters   << " "
582
                << " res_norm " << tolerance << "\n")
David Bommes's avatar
David Bommes committed
583
584
585
586
587
    ++n_cg_;
  }

  if(!converged && iter_full_solution_)
  {
588
    DEB_out_if( noisy_ > 2, 2, ", full ")
David Bommes's avatar
David Bommes committed
589
590
591
592

    if( gmm::mat_ncols( _A) > 0)
    {
      if(cholmod_step_done_)
593
	direct_solver_.update_system_gmm(_A);
David Bommes's avatar
David Bommes committed
594
      else
595
      {
596
	direct_solver_.calc_system_gmm(_A);
David Bommes's avatar
David Bommes committed
597
	cholmod_step_done_ = true;
598
      }
599
      direct_solver_.solve(_x,_rhs);
David Bommes's avatar
David Bommes committed
600
601

      ++n_full_;
602
    }
David Bommes's avatar
David Bommes committed
603
604
  }

605
  DEB_out_if( noisy_ > 2, 2, "\n")
David Bommes's avatar
David Bommes committed
606
607
608
}

//-----------------------------------------------------------------------------
609

David Bommes's avatar
David Bommes committed
610

611
void MISolver::solve_multiple_rounding( 
David Bommes's avatar
David Bommes committed
612
613
614
    CSCMatrix& _A, 
    Vecd&      _x, 
    Vecd&      _rhs, 
615
616
        Veci&      _to_round 
        )
David Bommes's avatar
David Bommes committed
617
{
618
  DEB_enter_func
David Bommes's avatar
David Bommes committed
619
  // StopWatch
620
  Base::StopWatch sw;
David Bommes's avatar
David Bommes committed
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
  double time_search_next_integer = 0;

  // some statistics
  n_local_ = 0;
  n_cg_    = 0;
  n_full_  = 0;

  // reset cholmod step flag
  cholmod_step_done_ = false;

  Veci to_round(_to_round);
  // copy to round vector and make it unique
  std::sort(to_round.begin(), to_round.end());
  Veci::iterator last_unique;
  last_unique = std::unique(to_round.begin(), to_round.end());
Max Lyon's avatar
Max Lyon committed
636
  size_t r = (size_t)(last_unique - to_round.begin());
David Bommes's avatar
David Bommes committed
637
638
  to_round.resize( r);

639
        // initialize old indices
David Bommes's avatar
David Bommes committed
640
641
642
643
644
645
  Veci old_idx(_rhs.size());
  for(unsigned int i=0; i<old_idx.size(); ++i)
    old_idx[i] = i;

  if( initial_full_solution_)
  {
646
647
648
649
650
651
                DEB_out_if( noisy_ > 2, 2, "initial full solution\n") 
    // TODO: we can throw more specific outcomes in the body of the fucntions below
    COMISO_THROW_if(!direct_solver_.calc_system_gmm(_A), 
      UNSPECIFIED_EIGEN_FAILURE);
    COMISO_THROW_if(!direct_solver_.solve(_x, _rhs), 
      UNSPECIFIED_EIGEN_FAILURE);
David Bommes's avatar
David Bommes committed
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666

    cholmod_step_done_ = true;

    ++n_full_;
  }

  // neighbors for local optimization
  Vecui neigh_i;

  // Vector for reduced solution
  Vecd xr(_x);

  // loop until solution computed
  for(unsigned int i=0; i<to_round.size(); ++i)
  {
667
668
    DEB_out_if(noisy_ > 0, 1, "Integer DOF's left: " << to_round.size()-(i+1) << " ")
        DEB_out_if(noisy_ > 1, 1, "residuum_norm: " << COMISO_GMM::residuum_norm( _A, xr, _rhs) << "\n")
David Bommes's avatar
David Bommes committed
669
670
671
672
673
674
675
676

    // position in round vector
    std::vector<int> tr_best;

    sw.start();

    RoundingSet rset;
    rset.set_threshold(multiple_rounding_threshold_);
677

David Bommes's avatar
David Bommes committed
678
679
680
681
    // find index yielding smallest rounding error
    for(unsigned int j=0; j<to_round.size(); ++j)
    {
      if( to_round[j] != -1)
682
      {
David Bommes's avatar
David Bommes committed
683
684
	int cur_idx = to_round[j];
	double rnd_error = fabs( ROUND(xr[cur_idx]) - xr[cur_idx]);
685

David Bommes's avatar
David Bommes committed
686
	rset.add(j, rnd_error);
687
688
689
      }
    }

David Bommes's avatar
David Bommes committed
690
691
692
693
694
    rset.get_ids( tr_best);

    time_search_next_integer += sw.stop();
  
    // nothing more to do?
Jan Möbius's avatar
Jan Möbius committed
695
    if( tr_best.empty() )
David Bommes's avatar
David Bommes committed
696
697
      break;

698
699
                DEB_out_if( noisy_ > 5, 5, 
      "round " << tr_best.size() << " variables simultaneously\n")
David Bommes's avatar
David Bommes committed
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717

    // clear neigh for local update
    neigh_i.clear();

    for(unsigned int j = 0; j<tr_best.size(); ++j)
    {
      int i_cur = to_round[tr_best[j]];

      // store rounded value
      double rnd_x = ROUND(xr[i_cur]);
      _x[ old_idx[i_cur] ] = rnd_x;

      // compute neighbors
      Col col = gmm::mat_const_col(_A, i_cur);
      ColIter it  = gmm::vect_const_begin( col);
      ColIter ite = gmm::vect_const_end  ( col);
      for(; it!=ite; ++it)
	if(it.index() != (unsigned int)i_cur)
Andreas Fabri's avatar
Andreas Fabri committed
718
	  neigh_i.push_back(static_cast<int>(it.index()));
David Bommes's avatar
David Bommes committed
719
720
721
722
723
724
725
726
727

      // eliminate var
      COMISO_GMM::fix_var_csc_symmetric( i_cur, rnd_x, _A, xr, _rhs);
      to_round[tr_best[j]] = -1;
    }

    // 3-stage update of solution w.r.t. roundings
    // local GS / CG / SparseCholesky
    update_solution( _A, xr, _rhs, neigh_i);
728
729
730
  }

  // final full solution?
David Bommes's avatar
David Bommes committed
731
  if( final_full_solution_)
732
  {
733
                DEB_out_if( noisy_ > 2, 2, "final full solution\n")
734
735
736

    if( gmm::mat_ncols( _A) > 0)
    {
David Bommes's avatar
David Bommes committed
737
      if(cholmod_step_done_)
738
	direct_solver_.update_system_gmm(_A);
David Bommes's avatar
David Bommes committed
739
      else
740
	direct_solver_.calc_system_gmm(_A);
David Bommes's avatar
David Bommes committed
741

742
      direct_solver_.solve( xr, _rhs);
David Bommes's avatar
David Bommes committed
743
      ++n_full_;
744
745
746
747
748
749
750
751
752
753
    }
  }

  // store solution values to result vector
  for(unsigned int i=0; i<old_idx.size(); ++i)
  {
    _x[ old_idx[i] ] = xr[i];
  }

  // output statistics
754
755
756
757
758
759
760
        DEB_out_if( stats_, 2, " *** Statistics of MiSo Solver ***"
                << "\n Number of CG    iterations  = " << n_cg_ 
        << "\n Number of LOCAL iterations  = " << n_local_ 
                << "\n Number of FULL  iterations  = " << n_full_ 
                << "\n Number of ROUNDING          = " << _to_round.size()
                << "\n time searching next integer = " 
        << time_search_next_integer / 1000.0 <<"s\n\n")
761
762
763
}


David Bommes's avatar
David Bommes committed
764
765
766
767
768
769
770
771
772
773
//-----------------------------------------------------------------------------


void
MISolver::solve_gurobi(
    CSCMatrix& _A,
    Vecd&      _x,
    Vecd&      _rhs,
    Veci&      _to_round)
{
774
  DEB_enter_func
David Bommes's avatar
David Bommes committed
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
#if COMISO_GUROBI_AVAILABLE

  // get round-indices in set
  std::set<int> to_round;
  for(unsigned int i=0; i<_to_round.size();++i)
    to_round.insert(_to_round[i]);

  try {
    GRBEnv env = GRBEnv();

    GRBModel model = GRBModel(env);

    // set time limite
    model.getEnv().set(GRB_DoubleParam_TimeLimit, gurobi_max_time_);

    unsigned int n = _rhs.size();

    // 1. allocate variables
    std::vector<GRBVar> vars;
    for( unsigned int i=0; i<n; ++i)
      if( to_round.count(i))
        vars.push_back( model.addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_INTEGER));
      else
        vars.push_back( model.addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_CONTINUOUS));

    // Integrate new variables
    model.update();

    // 2. setup_energy

    // build objective function from linear system E = x^tAx - 2x^t*rhs
    GRBQuadExpr objective;

    for(unsigned int i=0; i<_A.nc; ++i)
      for(unsigned int j=_A.jc[i]; j<_A.jc[i+1]; ++j)
      {
        objective += _A.pr[j]*vars[_A.ir[j]]*vars[i];
      }
    for(unsigned int i=0; i<n; ++i)
      objective -= 2*_rhs[i]*vars[i];

//    _A.jc[c+1]
//    _A.pr[write]
//    _A.ir[write]
//    _A.nc
//    _A.nr

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

    // 4. solve
    model.optimize();

    // 5. store result
    _x.resize(n);
    for(unsigned int i=0; i<n; ++i)
      _x[i] = vars[i].get(GRB_DoubleAttr_X);

834
    DEB_out(2, "GUROBI objective: " << model.get(GRB_DoubleAttr_ObjVal) << "\n")
David Bommes's avatar
David Bommes committed
835
836

  }
Jan Möbius's avatar
Jan Möbius committed
837
  catch(GRBException& e)
David Bommes's avatar
David Bommes committed
838
  {
839
    DEB_warning(2, "Error code = " << e.getErrorCode() << "[" << e.getMessage() << "]\n")
David Bommes's avatar
David Bommes committed
840
841
842
  }
  catch(...)
  {
843
    DEB_warning(1, "Exception during optimization")
David Bommes's avatar
David Bommes committed
844
845
846
  }

#else
847
  DEB_out(1,"GUROBI solver is not available, please install it...\n")
David Bommes's avatar
David Bommes committed
848
849
850
851
#endif
}


852
853
854
855
856
857
858
//----------------------------------------------------------------------------


void 
MISolver::
show_options_dialog()
{
859
860
  DEB_enter_func;
#if(COMISO_QT4_AVAILABLE)
861
862
  MISolverDialog* pd = new MISolverDialog(*this);
  pd->exec();
David Bommes's avatar
changed    
David Bommes committed
863
#else
864
  DEB_warning(1, "Qt not available to show solver dialog!!!")
865
866
867
868
#endif
}


869
// end namespace COMISO
870
}// ----------------------