ConstrainedSolverT.cc 44.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


26
27
28
29
30
31
//=============================================================================
//
//  CLASS MISolver - IMPLEMENTATION
//
//=============================================================================

32
#define COMISO_CONSTRAINEDSOLVER_C
33
34
35
36
//== INCLUDES =================================================================

#include "ConstrainedSolver.hh"
#include <gmm/gmm.h>
David Bommes's avatar
David Bommes committed
37
#include "GMM_Tools.hh"
38
#include <float.h>
Henrik Zimmer's avatar
Henrik Zimmer committed
39
#include <CoMISo/Utils/StopWatch.hh>
David Bommes's avatar
David Bommes committed
40
#include <CoMISo/Utils/MutablePriorityQueueT.hh>
41
42
43

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

44
namespace COMISO {
45
46
47
48

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


David Bommes's avatar
David Bommes committed
49
50
51
template<class RMatrixT, class CMatrixT, class VectorT, class VectorIT >
void 
ConstrainedSolver::
David Bommes's avatar
David Bommes committed
52
solve_const(	 const RMatrixT& _constraints,
David Bommes's avatar
David Bommes committed
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
		 const CMatrixT& _A, 
		 VectorT&  _x,
		 const VectorT&  _rhs,
		 const VectorIT& _idx_to_round,
		 double    _reg_factor,
		 bool      _show_miso_settings,
		 bool      _show_timings )
{
  // copy matrices
  RMatrixT constraints( gmm::mat_nrows(_constraints), gmm::mat_ncols(_constraints));
  gmm::copy(_constraints, constraints);

  CMatrixT A( gmm::mat_nrows(_A), gmm::mat_ncols(_A));
  gmm::copy(_A, A);

  // ... and vectors
  VectorT  rhs(_rhs);
  VectorIT idx_to_round(_idx_to_round);

  // call non-const function
  solve(constraints,
	A,
	_x,
	rhs,
	idx_to_round,
	_reg_factor,
	_show_miso_settings,
	_show_timings);
}


84
85
86
//-----------------------------------------------------------------------------


David Bommes's avatar
David Bommes committed
87
88
89
template<class RMatrixT, class VectorT, class VectorIT >
void 
ConstrainedSolver::
90
91
solve_const( const RMatrixT& _constraints,
	     const RMatrixT& _B,
David Bommes's avatar
David Bommes committed
92
	     VectorT&  _x,
93
	     const VectorIT& _idx_to_round,
David Bommes's avatar
David Bommes committed
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
	     double    _reg_factor,
	     bool      _show_miso_settings,
	     bool      _show_timings )
{
  // copy matrices
  RMatrixT constraints( gmm::mat_nrows(_constraints), gmm::mat_ncols(_constraints));
  gmm::copy(_constraints, constraints);

  RMatrixT B( gmm::mat_nrows(_B), gmm::mat_ncols(_B));
  gmm::copy(_B, B);

  // ... and vectors
  VectorIT idx_to_round(_idx_to_round);

  // call non-const function
  solve(constraints,
	B,
	_x,
	idx_to_round,
	_reg_factor,
	_show_miso_settings,
	_show_timings);
}


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


122
123
124
125
126
127
128
129
130
131
132
133
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 )
{
David Bommes's avatar
David Bommes committed
134
135
136
  // convert into quadratic system
  VectorT rhs;
  gmm::col_matrix< gmm::rsvector< double > > A;
David Bommes's avatar
David Bommes committed
137
  COMISO_GMM::factored_to_quadratic(_B, A, rhs);
David Bommes's avatar
David Bommes committed
138
139
140
141
142
143
144
145
146
147
148
149

  // solve
  solve( _constraints, A, _x, rhs, 
	 _idx_to_round, _reg_factor, 
	 _show_miso_settings,
	 _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;
150
 
David Bommes's avatar
David Bommes committed
151
152
//   // StopWatch for Timings
//   COMISO::StopWatch sw, sw2; sw.start(); sw2.start();
153

David Bommes's avatar
David Bommes committed
154
155
156
//   // c_elim[i] = index of variable which is eliminated in condition i
//   // or -1 if condition is invalid
//   std::vector<int> c_elim( ncons);
157

David Bommes's avatar
David Bommes committed
158
159
160
//   // 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();
161

David Bommes's avatar
David Bommes committed
162
163
//   // eliminate conditions and return column matrix Bcol
//   gmm::col_matrix< gmm::rsvector< double > > Bcol( nrows, ncols);
164

David Bommes's avatar
David Bommes committed
165
166
//   // reindexing vector
//   std::vector<int>                          new_idx;
167

David Bommes's avatar
David Bommes committed
168
169
//   eliminate_constraints( _constraints, _B, _idx_to_round, c_elim, new_idx, Bcol);
//   double time_eliminate = sw.stop()/1000.0; 
170

David Bommes's avatar
David Bommes committed
171
//   if( _show_timings) std::cerr << "Eliminated dimension: " << gmm::mat_nrows(Bcol) << " x " << gmm::mat_ncols(Bcol) << std::endl;
172

David Bommes's avatar
David Bommes committed
173
174
175
//   // setup and solve system
//   double time_setup = setup_and_solve_system( Bcol, _x, _idx_to_round, _reg_factor, _show_miso_settings);
//   sw.start();
176

David Bommes's avatar
David Bommes committed
177
//   //  double time_setup_solve = sw.stop()/1000.0; sw.start();
178
  
David Bommes's avatar
David Bommes committed
179
180
//   // restore eliminated vars to fulfill the given conditions
//   restore_eliminated_vars( _constraints, _x, c_elim, new_idx);
181

David Bommes's avatar
David Bommes committed
182
//   double time_resubstitute = sw.stop()/1000.0; sw.start();
183

David Bommes's avatar
David Bommes committed
184
//   //  double time_total = sw2.stop()/1000.0;
185

David Bommes's avatar
David Bommes committed
186
187
188
189
190
191
192
//   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;
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
}


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


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 )
{
212
213
214
215
216
  // show options dialog
  if( _show_miso_settings)
    miso_.show_options_dialog();


217
218
219
220
  int nrows = gmm::mat_nrows(_A);
  int ncols = gmm::mat_ncols(_A);
  int ncons = gmm::mat_nrows(_constraints);

221
222
  if( _show_timings) std::cerr << __FUNCTION__ << "\n Initital dimension: " << nrows << " x " << ncols 
			       << ", number of constraints: " << ncons << " use reordering: " << use_constraint_reordering() << std::endl;
223
224

  // StopWatch for Timings
225
  COMISO::StopWatch sw, sw2; sw.start(); sw2.start();
226
227
228
229
230
231

  // 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
232
233
234
235
236
  if(use_constraint_reordering())
    make_constraints_independent_reordering( _constraints, _idx_to_round, c_elim);
  else
    make_constraints_independent( _constraints, _idx_to_round, c_elim);

237
238
239
240
241
242
243
244
245
  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;

David Bommes's avatar
David Bommes committed
246
247
248
249
250
  if( _show_timings)
  {
    std::cerr << "Eliminated dimension: " << Acsc.nr << " x " << Acsc.nc << std::endl;
    std::cerr << "#nonzeros: " << gmm::nnz(Acsc) << std::endl;
  }
251
252

  sw.start();
David Bommes's avatar
David Bommes committed
253
  miso_.solve( Acsc, _x, _rhs, _idx_to_round);
254
255
  double time_miso = sw.stop()/1000.0; sw.start();

256
  rhs_update_table_.store(_constraints, c_elim, new_idx);
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
  // 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;
}


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


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
template<class RMatrixT, class VectorT >
void
ConstrainedSolver::
resolve_const(
     VectorT&  _x,
     const VectorT&  _rhs,
     double    _reg_factor,
     bool      _show_miso_settings,
     bool      _show_timings )
{
  VectorT  rhs(_rhs);

  // call non-const function
  resolve<RMatrixT>(_x,
  rhs,
  _reg_factor,
  _show_miso_settings,
  _show_timings);
}


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


template<class RMatrixT, class VectorT >
void
ConstrainedSolver::
resolve_const( const RMatrixT& _B,
       VectorT&  _x,
       double    _reg_factor,
       bool      _show_miso_settings,
       bool      _show_timings )
{
  resolve(_B,
  _x,
  _reg_factor,
  _show_miso_settings,
  _show_timings);
}


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


template<class RMatrixT, class VectorT >
void
ConstrainedSolver::
resolve(
    const RMatrixT& _B,
    VectorT&  _x,
    double    _reg_factor,
    bool      _show_miso_settings,
    bool      _show_timings )
{
  // extract rhs from quadratic system
  VectorT rhs;
 // gmm::col_matrix< gmm::rsvector< double > > A;
 // COMISO_GMM::factored_to_quadratic(_B, A, rhs);
  //TODO only compute rhs, not complete A for efficiency

  unsigned int m = gmm::mat_nrows(_B);
  unsigned int n = gmm::mat_ncols(_B);

  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;
  typedef typename gmm::linalg_traits<CRowT>::value_type            VecValT;

  gmm::resize(rhs, n-1);
  gmm::clear(rhs);
  for(unsigned int i = 0; i < m; ++i)
  {
    // get current condition row
    CRowT row       = gmm::mat_const_row( _B, i);
    RIter row_it    = gmm::vect_const_begin( row);
    RIter row_end   = gmm::vect_const_end( row);

    if(row_end == row_it) continue;
    --row_end;
    if(row_end.index() != n-1) continue;
    VecValT n_i = *row_end;
    while(row_end != row_it)
    {
      --row_end;
      rhs[row_end.index()] -= (*row_end) * n_i;
    }
  }

  // solve
  resolve<RMatrixT>(_x, rhs, _reg_factor,
   _show_miso_settings,
   _show_timings);
}


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


template<class RMatrixT, class VectorT >
void
ConstrainedSolver::
resolve(
    VectorT&  _x,
    VectorT&  _rhs,
    double    _reg_factor,
    bool      _show_miso_settings,
    bool      _show_timings )
{
  // show options dialog
  if( _show_miso_settings)
    miso_.show_options_dialog();

  // StopWatch for Timings
  COMISO::StopWatch sw;

  sw.start();
  // apply stored updates and eliminations to exchanged rhs
  rhs_update_table_.apply(_rhs);
  rhs_update_table_.eliminate(_rhs);

  miso_.resolve(_x, _rhs);

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

  // restore eliminated vars to fulfill the given conditions
  restore_eliminated_vars( rhs_update_table_.constraints_p_, _x, rhs_update_table_.c_elim_, rhs_update_table_.new_idx_);

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


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


413
414
415
416
417
418
419
420
template<class RMatrixT, class VectorIT >
void 
ConstrainedSolver::
make_constraints_independent(
    RMatrixT&         _constraints,
		VectorIT&         _idx_to_round,
		std::vector<int>& _c_elim)
{
David Bommes's avatar
David Bommes committed
421
  //  COMISO::StopWatch sw;
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
  // 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;
446
    int elim_int_j = -1;
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461

    // 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;
462
    double max_elim_val = -FLT_MAX;
463

Henrik Zimmer's avatar
   
Henrik Zimmer committed
464
465
466
467
    // new: gcd
    std::vector<int> v_gcd;
    v_gcd.resize(gmm::nnz(row),-1);
    int n_ints(0);
David Bommes's avatar
   
David Bommes committed
468
    bool gcd_update_valid(true);
Henrik Zimmer's avatar
   
Henrik Zimmer committed
469

470
471
472
473
474
475
    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 )
      {
476
        // found real valued var? -> finished (UPDATE: no not any more, find biggest real value to avoid x/1e-13)
477
478
        if( !roundmap[ cur_j ])
        {
479
480
481
482
483
484
          if( fabs(*row_it) > max_elim_val)
          {
            elim_j = cur_j;
            max_elim_val = fabs(*row_it);
          }
          //break;
485
486
        }
        else
487
        {
488
          double cur_row_val(fabs(*row_it));
Henrik Zimmer's avatar
   
Henrik Zimmer committed
489
490
491
492
          // gcd
          // if the coefficient of an integer variable is not an integer, then
          // the variable most problably will not be (expect if all coeffs are the same, e.g. 0.5)
          if( (double(int(cur_row_val))- cur_row_val) != 0.0)
David Bommes's avatar
   
David Bommes committed
493
494
495
496
497
	  {
// 	    std::cerr << __FUNCTION__ << " Warning: coefficient of integer variable is NOT integer: " 
// 		      << cur_row_val << std::endl;
	    gcd_update_valid = false;
	  }
Henrik Zimmer's avatar
   
Henrik Zimmer committed
498
499
500
501

          v_gcd[n_ints] = cur_row_val;
          ++n_ints;

502
503
          // store integer closest to 1, must be greater than epsilon_
          if( fabs(cur_row_val-1.0) < elim_val && cur_row_val > epsilon_)
504
          {
505
            elim_int_j   = cur_j;
Henrik Zimmer's avatar
   
Henrik Zimmer committed
506
            elim_val     = fabs(cur_row_val-1.0);
507
          }
508
        }
509
510
511
      }
    }

512
513
514
515
516
517
    // first try to eliminate a valid (>epsilon_) real valued variable (safer)
    if( max_elim_val > epsilon_)
    {}
    else // use the best found integer
      elim_j = elim_int_j;

518
519
520
    // if no integer or real valued variable greater than epsilon_ existed, then
    // elim_j is now -1 and this row is not considered as a valid constraint

521
522


Henrik Zimmer's avatar
   
Henrik Zimmer committed
523

524
525
526
    // store result
    _c_elim[i] = elim_j;
    // error check result
Henrik Zimmer's avatar
   
Henrik Zimmer committed
527
    if( elim_j == -1)
528
    {
Henrik Zimmer's avatar
   
Henrik Zimmer committed
529
530
      // redundant or incompatible?
      if( noisy_ > 0)
531
        if( fabs(gmm::mat_const_row(_constraints, i)[n_vars-1]) > epsilon_ )
David Bommes's avatar
   
David Bommes committed
532
533
          std::cerr << "Warning: incompatible condition: "
		    << fabs(gmm::mat_const_row(_constraints, i)[n_vars-1]) << std::endl;
Henrik Zimmer's avatar
   
Henrik Zimmer committed
534
535
      //         else
      //           std::cerr << "Warning: redundant condition:\n";
536
    }
Henrik Zimmer's avatar
   
Henrik Zimmer committed
537
538
539
    else
      if(roundmap[elim_j] && elim_val > 1e-6) 
      {
David Bommes's avatar
   
David Bommes committed
540
        if( do_gcd_ && gcd_update_valid)
Henrik Zimmer's avatar
   
Henrik Zimmer committed
541
542
543
544
545
546
547
548
549
550
        {
          // perform gcd update
          bool gcd_ok = update_constraint_gcd( _constraints, i, elim_j, v_gcd, n_ints);
          if( !gcd_ok)
            if( noisy_ > 0)
              std::cerr << __FUNCTION__ << " Warning: GCD update failed! " << gmm::mat_const_row(_constraints, i) << std::endl;
        }
        else
        {
          if( noisy_ > 0)
David Bommes's avatar
   
David Bommes committed
551
552
553
554
555
556
557
	  {
	    if( !do_gcd_)
	      std::cerr << __FUNCTION__ << " Warning: NO +-1 coefficient found, integer rounding cannot be guaranteed. Try using the GCD option! " << gmm::mat_const_row(_constraints, i) << std::endl;
	    else
	      std::cerr << __FUNCTION__ << " Warning: GCD of non-integer cannot be computed! " << gmm::mat_const_row(_constraints, i) << std::endl;

	  }
Henrik Zimmer's avatar
   
Henrik Zimmer committed
558
559
560
        }
      }

561
562
563
564
565

    // is this condition dependent?
    if( elim_j != -1 )
    {
      // get elim variable value
566
      double elim_val_cur = _constraints(i, elim_j);
567
568
569
570
571
572
573
574
575
576
577

      // 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)
        {
David Bommes's avatar
David Bommes committed
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
	  //          sw.start();
          add_row_simultaneously( c_it.index(), -(*c_it)/elim_val_cur, 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 RMatrixT, class VectorIT >
void 
ConstrainedSolver::
make_constraints_independent_reordering(
    RMatrixT&         _constraints,
		VectorIT&         _idx_to_round,
		std::vector<int>& _c_elim)
{
  //  COMISO::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);

  // init priority queue
  unsigned int nr = gmm::mat_nrows(_constraints);
  MutablePriorityQueueT<unsigned int, unsigned int> queue;
  queue.clear( nr );
  for(unsigned int i=0; i<nr; ++i)
  {
    int cur_nnz = gmm::nnz( gmm::mat_row(_constraints,i));
    if( _constraints(i,n_vars-1) != 0.0) --cur_nnz;

    queue.update(i, cur_nnz);
  }
  
  std::vector<bool> row_visited(nr, false);
  std::vector<unsigned int> row_ordering; row_ordering.reserve(nr);


  // for all conditions
  //  for(unsigned int i=0; i<gmm::mat_nrows(_constraints); ++i)
  while(!queue.empty())
  {
    // get next row
    unsigned int i = queue.get_next();
    row_ordering.push_back(i);
    row_visited[i] = true;

    // get elimination variable
    int elim_j = -1;
    int elim_int_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;
    double max_elim_val = -FLT_MAX;

    // new: gcd
    std::vector<int> v_gcd;
    v_gcd.resize(gmm::nnz(row),-1);
    int n_ints(0);
    bool gcd_update_valid(true);

    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 (UPDATE: no not any more, find biggest real value to avoid x/1e-13)
        if( !roundmap[ cur_j ])
        {
          if( fabs(*row_it) > max_elim_val)
          {
            elim_j = cur_j;
            max_elim_val = fabs(*row_it);
          }
          //break;
        }
        else
        {
          double cur_row_val(fabs(*row_it));
          // gcd
          // if the coefficient of an integer variable is not an integer, then
          // the variable most problably will not be (expect if all coeffs are the same, e.g. 0.5)
          if( (double(int(cur_row_val))- cur_row_val) != 0.0)
	  {
// 	    std::cerr << __FUNCTION__ << " Warning: coefficient of integer variable is NOT integer: " 
// 		      << cur_row_val << std::endl;
	    gcd_update_valid = false;
	  }

          v_gcd[n_ints] = cur_row_val;
          ++n_ints;

          // store integer closest to 1, must be greater than epsilon_
          if( fabs(cur_row_val-1.0) < elim_val && cur_row_val > epsilon_)
          {
            elim_int_j   = cur_j;
            elim_val     = fabs(cur_row_val-1.0);
          }
        }
      }
    }

    // first try to eliminate a valid (>epsilon_) real valued variable (safer)
    if( max_elim_val > epsilon_)
    {}
    else // use the best found integer
      elim_j = elim_int_j;

    // if no integer or real valued variable greater than epsilon_ existed, then
    // elim_j is now -1 and this row is not considered as a valid constraint




    // store result
    _c_elim[i] = elim_j;
    // error check result
    if( elim_j == -1)
    {
      // redundant or incompatible?
      if( noisy_ > 0)
        if( fabs(gmm::mat_const_row(_constraints, i)[n_vars-1]) > epsilon_ )
          std::cerr << "Warning: incompatible condition: "
		    << fabs(gmm::mat_const_row(_constraints, i)[n_vars-1]) << std::endl;
      //         else
      //           std::cerr << "Warning: redundant condition:\n";
    }
    else
      if(roundmap[elim_j] && elim_val > 1e-6) 
      {
        if( do_gcd_ && gcd_update_valid)
        {
          // perform gcd update
          bool gcd_ok = update_constraint_gcd( _constraints, i, elim_j, v_gcd, n_ints);
          if( !gcd_ok)
            if( noisy_ > 0)
              std::cerr << __FUNCTION__ << " Warning: GCD update failed! " << gmm::mat_const_row(_constraints, i) << std::endl;
        }
        else
        {
          if( noisy_ > 0)
	  {
	    if( !do_gcd_)
	      std::cerr << __FUNCTION__ << " Warning: NO +-1 coefficient found, integer rounding cannot be guaranteed. Try using the GCD option! " << gmm::mat_const_row(_constraints, i) << std::endl;
	    else
	      std::cerr << __FUNCTION__ << " Warning: GCD of non-integer cannot be computed! " << gmm::mat_const_row(_constraints, i) << std::endl;

	  }
        }
      }


    // is this condition dependent?
    if( elim_j != -1 )
    {
      // get elim variable value
      double elim_val_cur = _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)
	if( !row_visited[c_it.index()])
        {
	  //          sw.start();
782
          add_row_simultaneously( c_it.index(), -(*c_it)/elim_val_cur, gmm::mat_row(_constraints, i), _constraints, constraints_c);
783
784
785
          // 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;
David Bommes's avatar
David Bommes committed
786
787
788
789
790
791

	  int cur_idx = c_it.index();
	  int cur_nnz = gmm::nnz( gmm::mat_row(_constraints,cur_idx));
	  if( _constraints(cur_idx,n_vars-1) != 0.0) --cur_nnz;

	  queue.update(cur_idx, cur_nnz);
792
793
794
        }
    }
  }
David Bommes's avatar
David Bommes committed
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
  // // check result
  // for(unsigned int i=0; i<row_visited.size(); ++i)
  //   if( !row_visited[i])
  //     std::cerr <<"FAT ERROR: row " << i << " not visited...\n";
  


  // correct ordering
  RMatrixT c_tmp(gmm::mat_nrows(_constraints), gmm::mat_ncols(_constraints));
  gmm::copy(_constraints,c_tmp);

  // std::vector<int> elim_temp2(_c_elim);
  // std::sort(elim_temp2.begin(), elim_temp2.end());
  // std::cerr << elim_temp2 << std::endl;


  std::vector<int> elim_temp(_c_elim);
  _c_elim.resize(0); _c_elim.resize( elim_temp.size(),-1);

  for(unsigned int i=0; i<nr; ++i)
  {
    gmm::copy(gmm::mat_row(c_tmp,row_ordering[i]), gmm::mat_row(_constraints,i));
    _c_elim[i] = elim_temp[row_ordering[i]];
  }

  // // hack
  // elim_temp = _c_elim;
  // std::sort(elim_temp.begin(), elim_temp.end());
  // std::cerr << elim_temp << std::endl;

  // std::sort(row_ordering.begin(), row_ordering.end());
  // std::cerr << "row ordering: " << row_ordering << std::endl;
827
828
}

David Bommes's avatar
David Bommes committed
829

830
831
//-----------------------------------------------------------------------------

Henrik Zimmer's avatar
   
Henrik Zimmer committed
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
template<class RMatrixT>
bool
ConstrainedSolver::
update_constraint_gcd( RMatrixT& _constraints, 
                       int _row_i, 
                       int& _elim_j,
                       std::vector<int>& _v_gcd,
                       int& _n_ints)
{
  // find gcd
  double i_gcd = find_gcd(_v_gcd, _n_ints);

  if( fabs(i_gcd) == 1.0)
    return false;
  
  // divide by gcd
  typedef typename gmm::linalg_traits<RMatrixT>::const_sub_row_type CRowT;
  typedef typename gmm::linalg_traits<CRowT>::const_iterator        RIter;

  // get current constraint row
  RIter row_it    = gmm::vect_const_begin( gmm::mat_const_row( _constraints, _row_i));
  RIter row_end   = gmm::vect_const_end( gmm::mat_const_row( _constraints, _row_i));

  for( ; row_it!=row_end; ++row_it)
  {
    int cur_j = row_it.index();
    _constraints(_row_i, cur_j) = (*row_it)/i_gcd;
  }
  int elim_coeff = abs(_constraints(_row_i, _elim_j));
  if( elim_coeff != 1)
    std::cerr << __FUNCTION__ << " Error: elimination coefficient " << elim_coeff << " will (most probably) NOT lead to an integer solution!" << std::endl;
  return true;
}

//-----------------------------------------------------------------------------
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

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)
{
  // 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
David Bommes's avatar
David Bommes committed
920
  COMISO_GMM::eliminate_vars_idx( elim_cols, _new_idx, -1);
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939

  // 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());

940
941
942
943
944
945
946

  if( noisy_ > 2 )
  {
    std::cerr << __FUNCTION__ << "remaining         variables: " << gmm::mat_ncols(_Bcol) << std::endl;
    std::cerr << __FUNCTION__ << "remaining integer variables: " << _idx_to_round.size() << std::endl;
    std::cerr << __FUNCTION__ << std::endl;
  }
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
}


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


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)
{
966
  COMISO::StopWatch sw;
967
968
969
970
971
972
973
974
975
  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());

976
977
  rhs_update_table_.clear();

978
979
980
981
982
983
984
985
986
  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
987
988
      elim_varids.push_back(cur_j);
      rhs_update_table_.add_elim_id(cur_j);
989
990
991
992
993
994
995
996
997
998
999
1000

      // 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