ConstrainedSolverT.cc 25.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
//=============================================================================
//
//  CLASS MISolver - IMPLEMENTATION
//
//=============================================================================

#define ACG_CONSTRAINEDSOLVER_C
//== INCLUDES =================================================================

#include "ConstrainedSolver.hh"
#include <gmm/gmm.h>
#include <float.h>
Henrik Zimmer's avatar
Henrik Zimmer committed
13
#include <CoMISo/Utils/StopWatch.hh>
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
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
512
513
514
515
516
517
518
519
520
521
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
589
590
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
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

//== NAMESPACES ===============================================================

namespace ACG {

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


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


template<class RMatrixT, class VectorT, class VectorIT >
void 
ConstrainedSolver::
solve(
    RMatrixT& _constraints,
    RMatrixT& _B, 
    VectorT&  _x,
    VectorIT& _idx_to_round,
    double    _reg_factor,
    bool      _show_miso_settings,
    bool      _show_timings )
{
  int nrows = gmm::mat_nrows(_B);
  int ncols = gmm::mat_ncols(_B);
  int ncons = gmm::mat_nrows(_constraints);

  if( _show_timings) std::cerr << __FUNCTION__ << "\n Initial dimension: " << nrows << " x " << ncols << ", number of constraints: " << ncons << std::endl;
 
  // StopWatch for Timings
  ACG::StopWatch sw, sw2; sw.start(); sw2.start();

  // c_elim[i] = index of variable which is eliminated in condition i
  // or -1 if condition is invalid
  std::vector<int> c_elim( ncons);

  // apply sparse gauss elimination to make subsequent _constraints independent
  make_constraints_independent( _constraints, _idx_to_round, c_elim);
  double time_gauss = sw.stop()/1000.0; sw.start();

  // eliminate conditions and return column matrix Bcol
  gmm::col_matrix< gmm::rsvector< double > > Bcol( nrows, ncols);

  // reindexing vector
  std::vector<int>                          new_idx;

  eliminate_constraints( _constraints, _B, _idx_to_round, c_elim, new_idx, Bcol);
  double time_eliminate = sw.stop()/1000.0; sw.start();

  if( _show_timings) std::cerr << "Eliminated dimension: " << gmm::mat_nrows(Bcol) << " x " << gmm::mat_ncols(Bcol) << std::endl;

  // setup and solve system
  double time_setup = setup_and_solve_system( Bcol, _x, _idx_to_round, _reg_factor, _show_miso_settings);

  //  double time_setup_solve = sw.stop()/1000.0; sw.start();
  
  // restore eliminated vars to fulfill the given conditions
  restore_eliminated_vars( _constraints, _x, c_elim, new_idx);

  double time_resubstitute = sw.stop()/1000.0; sw.start();

  //  double time_total = sw2.stop()/1000.0;

  if( _show_timings) std::cerr << "Timings: \n\t" <<
    "Gauss Elimination  " << time_gauss          << " s\n\t" <<
    "System Elimination " << time_eliminate      << " s\n\t" <<
    "Setup              " << time_setup          << " s\n\t" <<
   // "Setup + Mi-Solver  " << time_setup_solve    << " s\n\t" <<
    "Resubstitution     " << time_resubstitute   << " s\n\t" << std::endl << std::endl;
    //"Total              " << time_total          << std::endl;
}


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


template<class RMatrixT, class CMatrixT, class VectorT, class VectorIT>
void 
ConstrainedSolver::
solve(
    RMatrixT& _constraints,
    CMatrixT& _A, 
    VectorT&  _x,
    VectorT&  _rhs,
    VectorIT& _idx_to_round,
    double    _reg_factor,
    bool      _show_miso_settings, 
    bool      _show_timings )
{
  int nrows = gmm::mat_nrows(_A);
  int ncols = gmm::mat_ncols(_A);
  int ncons = gmm::mat_nrows(_constraints);

  if( _show_timings) std::cerr << __FUNCTION__ << "\n Initital dimension: " << nrows << " x " << ncols << ", number of constraints: " << ncons << std::endl;

  // StopWatch for Timings
  ACG::StopWatch sw, sw2; sw.start(); sw2.start();

  // c_elim[i] = index of variable which is eliminated in condition i
  // or -1 if condition is invalid
  std::vector<int> c_elim( ncons);

  // apply sparse gauss elimination to make subsequent _conditions independent
  make_constraints_independent( _constraints, _idx_to_round, c_elim);
  double time_gauss = sw.stop()/1000.0; sw.start();

  // re-indexing vector
  std::vector<int>                          new_idx;

  gmm::csc_matrix< double > Acsc;
  eliminate_constraints( _constraints, _A, _x, _rhs, _idx_to_round, c_elim, new_idx, Acsc);
  double time_eliminate = sw.stop()/1000.0;

  if( _show_timings) std::cerr << "Eliminated dimension: " << Acsc.nr << " x " << Acsc.nc << std::endl;

  // create MISO solver
  ACG::MISolver miso;
  // show options dialog
  if( _show_miso_settings)
    miso.show_options_dialog();

  sw.start();
  miso.solve( Acsc, _x, _rhs, _idx_to_round);
  double time_miso = sw.stop()/1000.0; sw.start();

  // restore eliminated vars to fulfill the given conditions
  restore_eliminated_vars( _constraints, _x, c_elim, new_idx);

  double time_resubstitute = sw.stop()/1000.0; sw.start();
  double time_total = time_gauss + time_eliminate + time_miso + time_resubstitute;
  if( _show_timings) std::cerr << "Timings: \n\t" <<
    "\tGauss Elimination  " << time_gauss          << " s\n\t" <<
    "\tSystem Elimination " << time_eliminate      << " s\n\t" <<
    "\tMi-Solver          " << time_miso           << " s\n\t" <<
    "\tResubstitution     " << time_resubstitute   << " s\n\t" << 
    "\tTotal              " << time_total          << std::endl << std::endl;
}


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


template<class RMatrixT, class VectorIT >
void 
ConstrainedSolver::
make_constraints_independent(
    RMatrixT&         _constraints,
		VectorIT&         _idx_to_round,
		std::vector<int>& _c_elim)
{
  ACG::StopWatch sw;
  // number of variables
  int n_vars = gmm::mat_ncols(_constraints);

  // TODO Check: HZ added 14.08.09 
  _c_elim.clear();
  _c_elim.resize( gmm::mat_nrows(_constraints), -1);

  // build round map
  std::vector<bool> roundmap( n_vars, false);
  for(unsigned int i=0; i<_idx_to_round.size(); ++i)
    roundmap[_idx_to_round[i]] = true;

  // copy constraints into column matrix (for faster update via iterators)
  typedef gmm::wsvector<double>      CVector;
  typedef gmm::col_matrix< CVector > CMatrix;
  CMatrix constraints_c;
  gmm::resize(constraints_c, gmm::mat_nrows(_constraints), gmm::mat_ncols(_constraints));
  gmm::copy(_constraints, constraints_c);

  // for all conditions
  for(unsigned int i=0; i<gmm::mat_nrows(_constraints); ++i)
  {
    // get elimination variable
    int elim_j = -1;

    // iterate over current row, until variable found
    // first search for real valued variable
    // if not found for integers with value +-1
    // and finally take the smallest integer variable

    typedef typename gmm::linalg_traits<RMatrixT>::const_sub_row_type CRowT;
    typedef typename gmm::linalg_traits<RMatrixT>::sub_row_type       RowT;
    typedef typename gmm::linalg_traits<CRowT>::const_iterator        RIter;

    // get current condition row
    CRowT row       = gmm::mat_const_row( _constraints, i);
    RIter row_it    = gmm::vect_const_begin( row);
    RIter row_end   = gmm::vect_const_end( row);
    double elim_val = FLT_MAX;

    for(; row_it != row_end; ++row_it)
    {
      int cur_j = row_it.index();
      // do not use the constant part
      if(  cur_j != n_vars - 1 )
      {
        // found real valued var? -> finished
        if( !roundmap[ cur_j ])
        {
          elim_j = cur_j;
          break;
        }
        else
          // store smallest integer
          if( fabs(*row_it) < elim_val)
          {
            elim_j   = cur_j;
            elim_val = fabs(*row_it);
          }
      }
    }

    // store result
    _c_elim[i] = elim_j;
    // error check result
    if( elim_j == -1)
    {
      // redundant or incompatible?
      if( fabs(gmm::mat_const_row(_constraints, i)[n_vars-1]) > 1e-6 )
        std::cerr << "Warning: incompatible condition:\n";
      else
        std::cerr << "Warning: redundant condition:\n";
    }
    else
      if(roundmap[elim_j] && fabs(elim_val-1.0) > 1e-6)
        std::cerr << "Warning: eliminate non +-1 integer -> correct rounding cannot be guaranteed:\n" 
          << gmm::mat_const_row(_constraints, i) << std::endl;

    // is this condition dependent?
    if( elim_j != -1 )
    {
      // get elim variable value
      double elim_val = _constraints(i, elim_j);

      // copy col
      CVector col = constraints_c.col(elim_j);

      // iterate over column
      typename gmm::linalg_traits<CVector>::const_iterator c_it   = gmm::vect_const_begin(col);
      typename gmm::linalg_traits<CVector>::const_iterator c_end  = gmm::vect_const_end(col);

      for(; c_it != c_end; ++c_it)
        if( c_it.index() > i)
        {
          sw.start();
          add_row_simultaneously( c_it.index(), -(*c_it)/elim_val, gmm::mat_row(_constraints, i), _constraints, constraints_c);
          // make sure the eliminated entry is 0 on all other rows and not 1e-17
          _constraints( c_it.index(), elim_j) = 0;
          constraints_c(c_it.index(), elim_j) = 0;
        }
    }
  }
}


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


template<class SVector1T, class SVector2T, class VectorIT, class SVector3T>
void 
ConstrainedSolver::
eliminate_constraints( 
    gmm::row_matrix<SVector1T>& _constraints,
    gmm::row_matrix<SVector2T>& _B, 
    VectorIT&                   _idx_to_round,
    std::vector<int>&           _c_elim,
    std::vector<int>&           _new_idx,
    gmm::col_matrix<SVector3T>& _Bcol)
{
  std::cerr << __FUNCTION__ << std::endl;
  // copy into column matrix
  gmm::resize(_Bcol, gmm::mat_nrows(_B), gmm::mat_ncols(_B));
  gmm::copy( _B, _Bcol);

  // store columns which should be eliminated
  std::vector<int> elim_cols;
  elim_cols.reserve( _c_elim.size());

  for(unsigned int i=0; i<_c_elim.size(); ++i)
  {
    int cur_j = _c_elim[i];

    if( cur_j != -1)
    {
      double cur_val = _constraints(i,cur_j);

      // store index
      elim_cols.push_back(_c_elim[i]);

      // copy col
      SVector3T col = _Bcol.col(cur_j);

      // iterate over column
      typename gmm::linalg_traits<SVector3T>::const_iterator c_it   = gmm::vect_const_begin(col);
      typename gmm::linalg_traits<SVector3T>::const_iterator c_end  = gmm::vect_const_end(col);

      for(; c_it != c_end; ++c_it)
        add_row( c_it.index(), -(*c_it)/cur_val, gmm::mat_row(_constraints, i), _Bcol);
    }
  }

  // eliminate columns
  eliminate_columns( _Bcol, elim_cols);

  // TODO FIXME Size -1 ?!?!
  // init _new_idx vector
  _new_idx.resize(gmm::mat_ncols(_constraints));
  for(unsigned int i=0; i<_new_idx.size(); ++i)
    _new_idx[i] = i;

  // update _new_idx w.r.t. eliminated cols
  gmm::eliminate_vars_idx( elim_cols, _new_idx, -1);

  // update _idx_to_round (in place)
  std::vector<int> round_old(_idx_to_round);
  unsigned int wi = 0;
  for(unsigned int i=0; i<_idx_to_round.size(); ++i)
  {
    if(_new_idx[ _idx_to_round[i]] != -1)
    {
      _idx_to_round[wi] = _new_idx[_idx_to_round[i]];
      ++wi;
    }
  }
  
  // resize, sort and make unique
  _idx_to_round.resize(wi);

  std::sort(_idx_to_round.begin(), _idx_to_round.end());
  _idx_to_round.resize( std::unique(_idx_to_round.begin(), _idx_to_round.end()) -_idx_to_round.begin());

  std::cerr << "remaining         variables: " << gmm::mat_ncols(_Bcol) << std::endl;
  std::cerr << "remaining integer variables: " << _idx_to_round.size() << std::endl;
  std::cerr << std::endl;
}


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


template<class SVector1T, class SVector2T, class VectorIT, class CSCMatrixT>
void 
ConstrainedSolver::
eliminate_constraints(
    gmm::row_matrix<SVector1T>& _constraints,
    gmm::col_matrix<SVector2T>& _A, 
    std::vector<double>&        _x, 
    std::vector<double>&        _rhs, 
    VectorIT&                   _idx_to_round,
    std::vector<int>&           _v_elim,
    std::vector<int>&           _new_idx,
    CSCMatrixT&                 _Acsc)
{
  std::cerr << __FUNCTION__ << std::endl;

  ACG::StopWatch sw;
  sw.start();
  // define iterator on matrix A and on constraints C
  typedef typename gmm::linalg_traits<SVector2T>::const_iterator  AIter;
  typedef typename gmm::linalg_traits<SVector1T>::const_iterator  CIter;

  // store variable indices to be eliminated
  std::vector<int> elim_varids;
  elim_varids.reserve( _v_elim.size());

  for( unsigned int i=0; i < _v_elim.size(); ++i)
  {
    int cur_j = _v_elim[i];

    if( cur_j != -1)
    {
      double cur_val = _constraints(i, cur_j);

      // store index
      elim_varids.push_back(_v_elim[i]);

      // copy col
      SVector2T col ( _A.col( cur_j));

      // get a reference to current constraint vector 
      SVector1T& constraint( _constraints.row(i));

      // add cur_j-th row multiplied with constraint[k] to each row k
      // iterator of matrix column
      AIter col_it, col_end;
      
      // iterator of constraint
      CIter con_it  = gmm::vect_const_begin( constraint);
      CIter con_end = gmm::vect_const_end( constraint);

      // constraint rhs
      double constraint_rhs = constraint[ constraint.size()-1];

      //std::cerr << "constraint_rhs " << constraint_rhs << std::endl;
      // temporarliy set last element to zero (to avoid iterator finding it)
      constraint[ constraint.size()-1] = 0;

      double cur_rhs = _rhs[cur_j];

      // loop over all constraint entries over all column entries
      // should not hit last element (rhs) since set to zero
      for ( ; con_it != con_end; ++con_it )
      {
        col_it  = gmm::vect_const_begin( col );
        col_end = gmm::vect_const_end( col );
        for ( ; col_it != col_end; ++col_it )
          _A( con_it.index(), col_it.index() ) -= ( *col_it )*(( *con_it )/cur_val);

        _rhs[con_it.index()] -= cur_rhs * (( *con_it )/cur_val);
      }

      // TODO FIXME must use copy col (referens sometimes yields infinite loop below no col_it++?!?)
      SVector2T col_ref = _A.col(cur_j);
      
      // add cur_j-th col multiplied with condition[k] to each col k
      col_it  = gmm::vect_const_begin( col_ref );
      col_end = gmm::vect_const_end( col_ref );

      // loop over all column entries and over all constraint entries
      for ( ; col_it != col_end; ++col_it )
      {
        con_it  = gmm::vect_const_begin( constraint );
        con_end = gmm::vect_const_end( constraint );

        for ( ; con_it != con_end; ++con_it )
          _A( col_it.index(), con_it.index() ) -= ( *col_it )*(( *con_it )/cur_val);
        _rhs[col_it.index()] += constraint_rhs*( *col_it )/cur_val;
      }

      // reset last constraint entry to real value
      constraint[ constraint.size()-1] = constraint_rhs;
    }
  }
  std::cerr << "Constraints integrated " << sw.stop()/1000.0 << std::endl;

  // eliminate vars
  _Acsc.init_with_good_format(_A);
  sw.start();
  std::vector< double > elim_varvals( elim_varids.size(), 0);
  gmm::eliminate_csc_vars2( elim_varids, elim_varvals, _Acsc, _x, _rhs);

  std::cerr << "Constraints eliminated " << sw.stop()/1000.0 << std::endl;
  sw.start();
  // init _new_idx vector
  _new_idx.resize( mat_ncols(_constraints));
  for( unsigned int i=0; i<_new_idx.size(); ++i)
    _new_idx[i] = i;

  // update _new_idx w.r.t. eliminated cols
  gmm::eliminate_vars_idx( elim_varids, _new_idx, -1);

  // update _idx_to_round (in place)
  unsigned int wi = 0;
  for( unsigned int i=0; i<_idx_to_round.size(); ++i)
  {
    if(_new_idx[ _idx_to_round[i]] != -1)
    {
      _idx_to_round[wi] = _new_idx[_idx_to_round[i]];
      ++wi;
    }
  }

  // resize, sort and make unique
  _idx_to_round.resize(wi);

  std::sort(_idx_to_round.begin(), _idx_to_round.end());
  _idx_to_round.resize( std::unique(_idx_to_round.begin(), _idx_to_round.end()) -_idx_to_round.begin());
  std::cerr << "Indices reindexed " << sw.stop()/1000.0 << std::endl << std::endl;
}


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


template<class RowT, class MatrixT>
void 
ConstrainedSolver::
add_row( int       _row_i,
	 double    _coeff,
	 RowT      _row, 
	 MatrixT&  _mat )
{
  typedef typename gmm::linalg_traits<RowT>::const_iterator RIter;
  RIter r_it  = gmm::vect_const_begin(_row);
  RIter r_end = gmm::vect_const_end(_row);

  for(; r_it!=r_end; ++r_it)
    _mat(_row_i, r_it.index()) += _coeff*(*r_it);
}

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


template<class RowT, class RMatrixT, class CMatrixT>
void 
ConstrainedSolver::
add_row_simultaneously(	int       _row_i,
			double    _coeff,
			RowT      _row, 
			RMatrixT& _rmat,
			CMatrixT& _cmat )
{
  typedef typename gmm::linalg_traits<RowT>::const_iterator RIter;
  RIter r_it  = gmm::vect_const_begin(_row);
  RIter r_end = gmm::vect_const_end(_row);

  for(; r_it!=r_end; ++r_it)
  {
    _rmat(_row_i, r_it.index()) += _coeff*(*r_it);
    _cmat(_row_i, r_it.index()) += _coeff*(*r_it);
  }
}


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


template<class CMatrixT, class VectorT, class VectorIT>
double 
ConstrainedSolver::
setup_and_solve_system( CMatrixT& _B,
			VectorT&  _x,
			VectorIT& _idx_to_round,
			double    _reg_factor,
			bool      _show_miso_settings)
{
  std::cerr << __FUNCTION__ << std::endl;
  ACG::StopWatch s1;
  ACG::StopWatch sw; sw.start();
  unsigned int m = gmm::mat_nrows(_B);
  unsigned int n = gmm::mat_ncols(_B);

  s1.start();
  // set up B transposed
  CMatrixT Bt;
  gmm::resize( Bt, n, m);
  gmm::copy( gmm::transposed( _B), Bt);
  std::cerr << "Bt took " << s1.stop()/1000.0 << std::endl;
  s1.start();

  // setup BtB
  CMatrixT BtB;
  gmm::resize( BtB, n, n);
  gmm::mult( Bt, _B, BtB);
  std::cerr << "BtB took " << s1.stop()/1000.0 << std::endl;

  s1.start();
  // extract rhs
  std::vector< double > rhs( n);
  gmm::copy( gmm::scaled(gmm::mat_const_col( BtB, n - 1),-1.0), rhs);
  rhs.resize( n - 1);

  std::cerr << "rhs extract resize " << s1.stop()/1000.0 << std::endl;
  s1.start();
  // resize BtB to only contain the actual system matrix (and not the rhs)
  gmm::resize( BtB, n - 1, n - 1);

  std::cerr << "BtB resize took " << s1.stop()/1000.0 << std::endl;
  s1.start();
  _x.resize( n - 1);
  std::cerr << "x resize took " << s1.stop()/1000.0 << std::endl;

  // regularize if necessary
  if(_reg_factor != 0.0)
    gmm::regularize_hack(BtB, _reg_factor);
  s1.start();

  // BtB -> CSC
  CSCMatrix BtBCSC;
  BtBCSC.init_with_good_format( BtB);

  std::cerr << "CSC init " << s1.stop()/1000.0 << std::endl;
  double setup_time = sw.stop()/1000.0;
  
  // create solver
  ACG::MISolver miso;
  // show options dialog
  if( _show_miso_settings)
    miso.show_options_dialog();

  ACG::StopWatch misw;
  misw.start();
  // miso solve
  miso.solve( BtBCSC, _x, rhs, _idx_to_round);
  std::cerr << "Miso Time " << misw.stop()/1000.0 << "s." << std::endl << std::endl;
  return setup_time;
}


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


template<class RMatrixT, class VectorT >
void 
ConstrainedSolver::
restore_eliminated_vars( RMatrixT&         _constraints,
			 VectorT&          _x,
			 std::vector<int>& _c_elim,
			 std::vector<int>& _new_idx)
{
  // restore original ordering of _x
  _x.resize(_new_idx.size());
  // last variable is the constant term 1.0
  _x.back() = 1.0;

  // reverse iterate from prelast element
  for(int i=_new_idx.size()-2; i>= 0; --i)
  {
    if( _new_idx[i] != -1)
    {
      // error handling
      if( i < _new_idx[i]) std::cerr << "Warning: UNSAVE Ordering!!!\n";

      _x[i] = _x[_new_idx[i]];
    }
  }

  // reverse iterate
  for(int i=_c_elim.size()-1; i>=0; --i)
  {
    int cur_var = _c_elim[i];

    if( cur_var != -1)
    {
      // get variable value and set to zero
      double cur_val = _constraints(i, cur_var);
      _constraints(i, cur_var) = 0.0;

      _x[cur_var] = -gmm::vect_sp(_x, _constraints.row(i))/cur_val;
    }
  }

  // resize
  _x.resize(_x.size()-1);
}


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


template<class RMatrixT, class VectorT, class VectorIT >
void 
ConstrainedSolver::
verify_mi_factored( const RMatrixT& _conditions,
		    const RMatrixT& _B, 
		    const VectorT&  _x,
		    const VectorIT& _idx_to_round )
{
  std::cerr << "######### Verify Constrained Solver Result ############\n";

  // create extended x vector
  std::vector<double> x(_x);
  x.resize(x.size()+1);
  x.back() = 1.0;

  // verify conditions
  std::vector<double> a(gmm::mat_nrows(_conditions));

  gmm::mult(_conditions, x, a);

  int conditions_not_ok = 0;
  for(unsigned int i=0; i<a.size(); ++i)
    if( a[i] > 1e-6)
    {
      ++conditions_not_ok;
    }

  if( conditions_not_ok == 0)
    std::cerr << "all conditions are ok!\n";
  else
    std::cerr << conditions_not_ok 
	      << " conditions are not fullfilled: " 
	      << std::endl;

  // verify rounding
  int roundings_not_ok = 0;
  for(unsigned int i=0; i<_idx_to_round.size(); ++i)
  {
    double d = _x[_idx_to_round[i]];
    if( fabs(d-round(d)) > 1e-6)
      ++roundings_not_ok;
  }
  
  if( roundings_not_ok)
    std::cerr << roundings_not_ok << " Integer variables are not rounded\n";
  else
    std::cerr << "all Integer roundings are ok\n";

  // evaluate energy
  VectorT Bx(x);
  gmm::mult(_B, x, Bx);
  std::cerr << "Total energy: " << gmm::vect_sp(Bx, Bx) << std::endl;

  std::cerr << "######### FINISHED ############\n";
}



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


template<class RMatrixT, class CMatrixT, class VectorT>
double 
ConstrainedSolver::verify_constrained_system( 
    const RMatrixT& _conditions,
    const CMatrixT& _A,
    const VectorT&  _x,
    const VectorT&  _rhs)
{
  typedef typename gmm::linalg_traits<RMatrixT>::const_sub_row_type RowT;
  typedef typename gmm::linalg_traits<RowT>::const_iterator RIter;

  // Residual
  std::cerr << "MATRIX " << _A << std::endl;
  std::cerr << "X " << _x << std::endl;
  std::cerr << "RHS " << _rhs << std::endl;
  std::cerr << "CONDITIONS" << _conditions << std::endl;
  VectorT Ax( _x.size());
  gmm::mult(_A, _x, Ax);

  gmm::add(_rhs, gmm::scaled(Ax, -1.0), Ax);
  double norm = gmm::vect_norm2(Ax);
  //std::cerr << __FUNCTION__ << ": Error residual: " << norm << " vector : " << Ax << std::endl;

  std::cerr << __FUNCTION__ << ": Checking constraints..." << std::endl;

  unsigned int row_cond = gmm::mat_nrows( _conditions);
  unsigned int col_cond = gmm::mat_ncols( _conditions);
  bool all_conditions_ok = true;
  for( unsigned int r = 0; r < row_cond; ++r)
  {
    double cond_value = 0.0;
    RowT row      = gmm::mat_const_row( _conditions, r);
    RIter row_it  = gmm::vect_const_begin( row);
    RIter row_end = gmm::vect_const_end( row);
    //std::cerr << "\t checking row : " << row << std::endl;

    for( ; row_it != row_end; ++row_it)
    {
      if( row_it.index() == col_cond -1)
        cond_value += (*row_it);
      else
        cond_value += _x[row_it.index()]*(*row_it);
    }
    //std::cerr << "\t Value is : " << cond_value << std::endl;
    //std::cerr << "--- --- --- --- ---\n";
    if( cond_value != 0.0)
    {
      std::cerr << "\t Error on row " << r << " with vector " << row << " and condition value " << cond_value << std::endl;
      all_conditions_ok = false;
    }
  }
  std::cerr << __FUNCTION__ << (all_conditions_ok? ": All conditions ok!" : ": Some conditions not ok!") << std::endl;
  return norm;
}

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


template<class RMatrixT, class CMatrixT, class VectorT, class VectorIT>
double
ConstrainedSolver::
verify_constrained_system_round( 
              const RMatrixT& _conditions,
              const CMatrixT& _A,
              const VectorT&  _x,
              const VectorT&  _rhs,
              const VectorIT& _idx_to_round)
{
 std::cerr << "MATRIX " << _A << std::endl;
  std::cerr << "X " << _x << std::endl;
  std::cerr << "RHS " << _rhs << std::endl;
  std::cerr << "CONDITIONS" << _conditions << std::endl;
  
  // test integer roundings
  std::cerr << __FUNCTION__ << ": Testing integer roundings..." << std::endl;
  bool all_roundings_ok = true;

  for( unsigned int i = 0; i < _idx_to_round.size(); ++i)
    if(fabs(ROUND(_x[_idx_to_round[i]])-_x[_idx_to_round[i]]) > 1e-10)
    {
      std::cerr << "\t Warning: variable " << _idx_to_round[i] << " was not rounded!" << " Value is = " << _x[_idx_to_round[i]] << std::endl;
      all_roundings_ok = false;
    }
  std::cerr << __FUNCTION__ << (all_roundings_ok? ": All roundings ok!" : ": Some roundings not ok!") << std::endl;

  // also test other stuff
  return verify_constrained_system(_conditions, _A, _x, _rhs);
}

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


template<class CMatrixT>
void 
ConstrainedSolver::eliminate_columns( CMatrixT& _M,
				      const std::vector< int >& _columns)
{
  // nothing to do?
  if( _columns.size() == 0) return;

  // eliminate columns in place by first copying to the right place
  // and a subsequent resize
  std::vector< int > columns( _columns);
  std::sort( columns.begin(), columns.end());

  std::vector< int >::iterator col_it  = columns.begin();
  std::vector< int >::iterator col_end = columns.end();

  int next_i = *col_it;
  for( int i = *col_it; i < (int)_M.ncols(); ++i)
  {
    if( col_it != col_end && i == *col_it)
    {
      ++col_it;
    }
    else
    {
      _M.col(next_i) = _M.col(i);
      ++next_i;
    }
  }
  gmm::resize( _M, _M.nrows(), _M.ncols() - columns.size());
}


//=============================================================================
} // namespace ACG
//=============================================================================