inmost_dense.h 29.3 KB
Newer Older
1
2
3
4
5
6
#ifndef INMOST_DENSE_INCLUDED
#define INMOST_DENSE_INCLUDED
#include "inmost_common.h"
#if defined(USE_AUTODIFF)
#include "inmost_expression.h"
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
7
#include <iomanip>
8
9
10
11
12
13
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

// Matrix with n columns and m rows
//   __m__
//  |     |
// n|     |
//  |_____|
//
// todo: 
// 1. expression templates for operations
//    (???) how to for multiplication?
// 2. (ok) template matrix type for AD variables


namespace INMOST
{
  

  template<class A, class B> struct Promote;
  template<> struct Promote<INMOST_DATA_REAL_TYPE, INMOST_DATA_REAL_TYPE> {typedef INMOST_DATA_REAL_TYPE type;};
#if defined(USE_AUTODIFF)
  template<> struct Promote<INMOST_DATA_REAL_TYPE, variable>  {typedef variable type;};
  template<> struct Promote<variable, INMOST_DATA_REAL_TYPE>  {typedef variable type;};
  template<> struct Promote<variable, variable> {typedef variable type;};
#else
  INMOST_DATA_REAL_TYPE get_value(INMOST_DATA_REAL_TYPE x) {return x;}
#endif

  template<typename Var>
  class Matrix
  {
  public:
    typedef unsigned enumerator;
  protected:
    array<Var> space;
    enumerator n, m;
  

Kirill Terekhov's avatar
Kirill Terekhov committed
45
46
    static Var sign_func(const Var & a, const Var & b) {return (b >= 0.0 ? fabs(a) : -fabs(a));}
	  static INMOST_DATA_REAL_TYPE max_func(INMOST_DATA_REAL_TYPE x, INMOST_DATA_REAL_TYPE y) { return x > y ? x : y; }
47
48
49
	  static Var pythag(const Var & a, const Var & b)
	  {
		  Var at = fabs(a), bt = fabs(b), ct, result;
Kirill Terekhov's avatar
Kirill Terekhov committed
50
51
		  if (at > bt)       { ct = bt / at; result = at * sqrt(1.0 + ct * ct); }
		  else if (bt > 0.0) { ct = at / bt; result = bt * sqrt(1.0 + ct * ct); }
52
53
54
55
		  else result = 0.0;
		  return result;
	  }
  public:
Kirill Terekhov's avatar
Kirill Terekhov committed
56
57
58
59
60
61
62
63
64
65
    void RemoveRow(enumerator row)
    {
      for(enumerator k = row+1; k < n; ++k)
      {
        for(enumerator l = 0; l < m; ++l)
          (*this)(k-1,l) = (*this)(k,l);
      }
      space.resize((n-1)*m);
      --n;
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
66
67
68
69
70
71
72
73
74
75
76
    void RemoveRows(enumerator first, enumerator last)
    {
      enumerator shift = last-first;
      for(enumerator k = last+1; k < n; ++k)
      {
        for(enumerator l = 0; l < m; ++l)
        (*this)(k-shift-1,l) = (*this)(k,l);
      }
      space.resize((n-shift)*m);
      n-=shift;
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
77
78
    void RemoveColumn(enumerator col)
    {
Kirill Terekhov's avatar
Kirill Terekhov committed
79
      Matrix<Var> tmp(n,m-1);
Kirill Terekhov's avatar
Kirill Terekhov committed
80
81
      for(enumerator k = 0; k < n; ++k)
      {
Kirill Terekhov's avatar
Kirill Terekhov committed
82
83
        for(enumerator l = 0; l < col; ++l)
            tmp(k,l) = (*this)(k,l);
Kirill Terekhov's avatar
Kirill Terekhov committed
84
        for(enumerator l = col+1; l < m; ++l)
Kirill Terekhov's avatar
Kirill Terekhov committed
85
          tmp(k,l-1) = (*this)(k,l);
Kirill Terekhov's avatar
Kirill Terekhov committed
86
      }
Kirill Terekhov's avatar
Kirill Terekhov committed
87
      this->Swap(tmp);
Kirill Terekhov's avatar
Kirill Terekhov committed
88
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
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
      void RemoveColumns(enumerator first, enumerator last)
      {
          enumerator shift = last-first;
          Matrix<Var> tmp(n,m-shift);
          for(enumerator k = 0; k < n; ++k)
          {
              for(enumerator l = 0; l < first; ++l)
                  tmp(k,l) = (*this)(k,l);
              for(enumerator l = last+1; l < m; ++l)
                  tmp(k,l-shift-1) = (*this)(k,l);
          }
          this->Swap(tmp);
      }
      void RemoveSubset(enumerator firstrow, enumerator lastrow, enumerator firstcol, enumerator lastcol)
      {
          enumerator shiftrow = lastrow-firstrow;
          enumerator shiftcol = lastcol-firstcol;
          Matrix<Var> tmp(n-shiftrow, m-shiftcol);
          for(enumerator k = 0; k < firstrow; ++k)
          {
              for(enumerator l = 0; l < firstcol; ++l)
                  tmp(k,l) = (*this)(k,l);
              for(enumerator l = lastcol+1; l < m; ++l)
                  tmp(k,l-shiftcol-1) = (*this)(k,l);
          }
          for(enumerator k = lastrow+1; k < n; ++k)
          {
              for(enumerator l = 0; l < firstcol; ++l)
                  tmp(k-shiftrow-1,l) = (*this)(k,l);
              for(enumerator l = lastcol+1; l < m; ++l)
                  tmp(k-shiftrow-1,l-shiftcol-1) = (*this)(k,l);
          }
          this->Swap(tmp);
      }
123
124
125
126
127
128
    void Swap(Matrix & b)
    {
      space.swap(b.space);
      std::swap(n,b.n);
      std::swap(m,b.m);
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
129
130
131
132
133
134
135
    /// Singular value decomposition.
    /// Reconstruct matrix: A = U*Sigma*V.Transpose().
    /// @param U Left unitary matrix, U^T U = I.
    /// @param Sigma Diagonal matrix with singular values.
    /// @param V Right unitary matrix, not transposed.
    /// @param order_singular_values
    bool SVD(Matrix & U, Matrix & Sigma, Matrix & V, bool order_singular_values = true)
136
137
138
    {
      int flag, i, its, j, jj, k, l, nm;
      Var c, f, h, s, x, y, z;
Kirill Terekhov's avatar
Kirill Terekhov committed
139
140
      Var g = 0.0, scale = 0.0;
      INMOST_DATA_REAL_TYPE anorm = 0.0;
141
142
      if (n < m) 
      {
Kirill Terekhov's avatar
Kirill Terekhov committed
143
        bool success = Transpose().SVD(U,Sigma,V);
144
145
        if( success )
        {
Kirill Terekhov's avatar
Kirill Terekhov committed
146
          U.Swap(V);
147
          U = U.Transpose();
Kirill Terekhov's avatar
Kirill Terekhov committed
148
          V = V.Transpose();
149
150
151
152
153
154
155
156
157
          return true;
        }
        else return false;
      } //m <= n
      array<Var> _rv1(m);
      shell<Var> rv1(_rv1);
      U = (*this);
      Sigma.Resize(m,m);
      Sigma.Zero();
Kirill Terekhov's avatar
Kirill Terekhov committed
158
      V.Resize(m,m);
159
160
161
  
      std::swap(n,m); //this how original algorithm takes it
      // Householder reduction to bidiagonal form
Kirill Terekhov's avatar
Kirill Terekhov committed
162
      for (i = 0; i < (int)n; i++) 
163
164
165
166
167
      {
        // left-hand reduction
        l = i + 1;
        rv1[i] = scale * g;
        g = s = scale = 0.0;
Kirill Terekhov's avatar
Kirill Terekhov committed
168
        if (i < (int)m) 
169
        {
Kirill Terekhov's avatar
Kirill Terekhov committed
170
          for (k = i; k < (int)m; k++) scale += fabs(U(k,i));
171
172
          if (get_value(scale)) 
          {
Kirill Terekhov's avatar
Kirill Terekhov committed
173
            for (k = i; k < (int)m; k++) 
174
            {
Kirill Terekhov's avatar
Kirill Terekhov committed
175
176
              U(k,i) /= scale;
              s += U(k,i) * U(k,i);
177
            }
Kirill Terekhov's avatar
Kirill Terekhov committed
178
            f = U(i,i);
179
180
            g = -sign_func(sqrt(s), f);
            h = f * g - s;
Kirill Terekhov's avatar
Kirill Terekhov committed
181
            U(i,i) = f - g;
182
183
            if (i != n - 1) 
            {
Kirill Terekhov's avatar
Kirill Terekhov committed
184
              for (j = l; j < (int)n; j++) 
185
              {
Kirill Terekhov's avatar
Kirill Terekhov committed
186
                for (s = 0.0, k = i; k < (int)m; k++) s += U(k,i) * U(k,j);
187
                f = s / h;
Kirill Terekhov's avatar
Kirill Terekhov committed
188
                for (k = i; k < (int)m; k++) U(k,j) += f * U(k,i);
189
190
              }
            }
Kirill Terekhov's avatar
Kirill Terekhov committed
191
            for (k = i; k < (int)m; k++) U(k,i) *= scale;
192
193
          }
        }
Kirill Terekhov's avatar
Kirill Terekhov committed
194
        Sigma(i,i) = scale * g;
195
196
        // right-hand reduction
        g = s = scale = 0.0;
Kirill Terekhov's avatar
Kirill Terekhov committed
197
        if (i < (int)m && i != n - 1) 
198
        {
Kirill Terekhov's avatar
Kirill Terekhov committed
199
          for (k = l; k < (int)n; k++) scale += fabs(U(i,k));
200
201
          if (get_value(scale)) 
          {
Kirill Terekhov's avatar
Kirill Terekhov committed
202
            for (k = l; k < (int)n; k++) 
203
            {
Kirill Terekhov's avatar
Kirill Terekhov committed
204
205
              U(i,k) = U(i,k)/scale;
              s += U(i,k) * U(i,k);
206
            }
Kirill Terekhov's avatar
Kirill Terekhov committed
207
            f = U(i,l);
208
209
            g = -sign_func(sqrt(s), f);
            h = f * g - s;
Kirill Terekhov's avatar
Kirill Terekhov committed
210
211
            U(i,l) = f - g;
            for (k = l; k < (int)n; k++) rv1[k] = U(i,k) / h;
212
213
            if (i != m - 1) 
            {
Kirill Terekhov's avatar
Kirill Terekhov committed
214
              for (j = l; j < (int)m; j++) 
215
              {
Kirill Terekhov's avatar
Kirill Terekhov committed
216
217
                for (s = 0.0, k = l; k < (int)n; k++) s += U(j,k) * U(i,k);
                for (k = l; k < (int)n; k++) U(j,k) += s * rv1[k];
218
219
              }
            }
Kirill Terekhov's avatar
Kirill Terekhov committed
220
            for (k = l; k < (int)n; k++) U(i,k) *= scale;
221
222
          }
        }
Kirill Terekhov's avatar
Kirill Terekhov committed
223
        anorm = max_func(anorm,fabs(get_value(Sigma(i,i))) + fabs(get_value(rv1[i])));
224
225
226
227
228
      }

      // accumulate the right-hand transformation
      for (i = n - 1; i >= 0; i--) 
      {
Kirill Terekhov's avatar
Kirill Terekhov committed
229
        if (i < (int)(n - 1)) 
230
231
232
        {
          if (get_value(g)) 
          {
Kirill Terekhov's avatar
Kirill Terekhov committed
233
            for (j = l; j < (int)n; j++) V(j,i) = ((U(i,j) / U(i,l)) / g);
234
            // double division to avoid underflow
Kirill Terekhov's avatar
Kirill Terekhov committed
235
            for (j = l; j < (int)n; j++) 
236
            {
Kirill Terekhov's avatar
Kirill Terekhov committed
237
238
              for (s = 0.0, k = l; k < (int)n; k++) s += U(i,k) * V(k,j);
              for (k = l; k < (int)n; k++) V(k,j) += s * V(k,i);
239
240
            }
          }
Kirill Terekhov's avatar
Kirill Terekhov committed
241
          for (j = l; j < (int)n; j++) V(i,j) = V(j,i) = 0.0;
242
        }
Kirill Terekhov's avatar
Kirill Terekhov committed
243
        V(i,i) = 1.0;
244
245
246
247
248
249
250
251
        g = rv1[i];
        l = i;
      }

      // accumulate the left-hand transformation
      for (i = n - 1; i >= 0; i--) 
      {
        l = i + 1;
Kirill Terekhov's avatar
Kirill Terekhov committed
252
253
254
255
        g = Sigma(i,i);
        if (i < (int)(n - 1)) 
          for (j = l; j < (int)n; j++) 
            U(i,j) = 0.0;
256
257
258
259
260
        if (get_value(g)) 
        {
          g = 1.0 / g;
          if (i != n - 1) 
          {
Kirill Terekhov's avatar
Kirill Terekhov committed
261
            for (j = l; j < (int)n; j++) 
262
            {
Kirill Terekhov's avatar
Kirill Terekhov committed
263
264
265
              for (s = 0.0, k = l; k < (int)m; k++) s += (U(k,i) * U(k,j));
              f = (s / U(i,i)) * g;
              for (k = i; k < (int)m; k++) U(k,j) += f * U(k,i);
266
267
            }
          }
Kirill Terekhov's avatar
Kirill Terekhov committed
268
          for (j = i; j < (int)m; j++) U(j,i) = U(j,i)*g;
269
        }
Kirill Terekhov's avatar
Kirill Terekhov committed
270
271
        else for (j = i; j < (int)m; j++) U(j,i) = 0.0;
        U(i,i) += 1;
272
273
274
275
276
277
278
279
280
281
282
      }

      // diagonalize the bidiagonal form
      for (k = n - 1; k >= 0; k--) 
      {// loop over singular values
        for (its = 0; its < 30; its++) 
        {// loop over allowed iterations
          flag = 1;
          for (l = k; l >= 0; l--) 
          {// test for splitting
            nm = l - 1;
Kirill Terekhov's avatar
Kirill Terekhov committed
283
            if (fabs(get_value(rv1[l])) + anorm == anorm) 
284
285
286
287
            {
              flag = 0;
              break;
            }
Kirill Terekhov's avatar
Kirill Terekhov committed
288
            if (fabs(get_value(Sigma(nm,nm))) + anorm == anorm) 
289
290
291
292
293
294
295
296
297
              break;
          }
          if (flag) 
          {
            c = 0.0;
            s = 1.0;
            for (i = l; i <= k; i++) 
            {
              f = s * rv1[i];
Kirill Terekhov's avatar
Kirill Terekhov committed
298
              if (fabs(get_value(f)) + anorm != anorm) 
299
              {
Kirill Terekhov's avatar
Kirill Terekhov committed
300
                g = Sigma(i,i);
301
                h = pythag(f, g);
Kirill Terekhov's avatar
Kirill Terekhov committed
302
                Sigma(i,i) = h; 
303
304
305
                h = 1.0 / h;
                c = g * h;
                s = (- f * h);
Kirill Terekhov's avatar
Kirill Terekhov committed
306
                for (j = 0; j < (int)m; j++) 
307
                {
Kirill Terekhov's avatar
Kirill Terekhov committed
308
309
310
311
                  y = U(j,nm);
                  z = U(j,i);
                  U(j,nm) = (y * c + z * s);
                  U(j,i) = (z * c - y * s);
312
313
314
315
                }
              }
            }
          }
Kirill Terekhov's avatar
Kirill Terekhov committed
316
          z = Sigma(k,k);
317
318
319
320
          if (l == k) 
          {// convergence
            if (z < 0.0) 
            {// make singular value nonnegative
Kirill Terekhov's avatar
Kirill Terekhov committed
321
322
              Sigma(k,k) = -z;
              for (j = 0; j < (int)n; j++) V(j,k) = -V(j,k);
323
324
325
326
327
328
329
330
331
332
            }
            break;
          }
          if (its >= 30) 
          {
            std::cout << "No convergence after " << its << " iterations" << std::endl;
            std::swap(n,m);
            return false;
          }
          // shift from bottom 2 x 2 minor
Kirill Terekhov's avatar
Kirill Terekhov committed
333
          x = Sigma(l,l);
334
          nm = k - 1;
Kirill Terekhov's avatar
Kirill Terekhov committed
335
          y = Sigma(nm,nm);
336
337
338
339
340
341
342
343
344
345
346
          g = rv1[nm];
          h = rv1[k];
          f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2.0 * h * y);
          g = pythag(f, 1.0);
          f = ((x - z) * (x + z) + h * ((y / (f + sign_func(g, f))) - h)) / x;
          // next QR transformation
          c = s = 1.0;
          for (j = l; j <= nm; j++) 
          {
            i = j + 1;
            g = rv1[i];
Kirill Terekhov's avatar
Kirill Terekhov committed
347
            y = Sigma(i,i);
348
349
350
351
352
353
354
355
356
357
            h = s * g;
            g = c * g;
            z = pythag(f, h);
            rv1[j] = z;
            c = f / z;
            s = h / z;
            f = x * c + g * s;
            g = g * c - x * s;
            h = y * s;
            y = y * c;
Kirill Terekhov's avatar
Kirill Terekhov committed
358
            for (jj = 0; jj < (int)n; jj++) 
359
            {
Kirill Terekhov's avatar
Kirill Terekhov committed
360
361
362
363
              x = V(jj,j);
              z = V(jj,i);
              V(jj,j) = (x * c + z * s);
              V(jj,i) = (z * c - x * s);
364
365
            }
            z = pythag(f, h);
Kirill Terekhov's avatar
Kirill Terekhov committed
366
            Sigma(j,j) = z;
367
368
369
370
371
372
373
374
            if (z) 
            {
              z = 1.0 / z;
              c = f * z;
              s = h * z;
            }
            f = (c * g) + (s * y);
            x = (c * y) - (s * g);
Kirill Terekhov's avatar
Kirill Terekhov committed
375
            for (jj = 0; jj < (int)m; jj++) 
376
            {
Kirill Terekhov's avatar
Kirill Terekhov committed
377
378
379
380
              y = U(jj,j);
              z = U(jj,i);
              U(jj,j) = (y * c + z * s);
              U(jj,i) = (z * c - y * s);
381
382
383
384
            }
          }
          rv1[l] = 0.0;
          rv1[k] = f;
Kirill Terekhov's avatar
Kirill Terekhov committed
385
          Sigma(k,k) = x;
386
387
        }
      }
Kirill Terekhov's avatar
Kirill Terekhov committed
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
      //CHECK THIS!
      if( order_singular_values )
      {
        for(i = 0; i < (int)n; i++)
		    {
			    k = i;
			    for(j = i+1; j < (int)n; ++j)
				    if( Sigma(k,k) < Sigma(j,j) ) k = j;
			    Var temp;
			    if( Sigma(k,k) > Sigma(i,i) )
			    {
				    temp       = Sigma(k,k);
				    Sigma(k,k) = Sigma(i,i);
				    Sigma(i,i) = temp;
            // U is m by n
            for(int j = 0; j < (int)m; ++j)
				    {
					    temp   = U(j,k);
					    U(j,k) = U(j,i);
					    U(j,i) = temp;
            }
            // V is n by n
            for(int j = 0; j < (int)n; ++j)
            {
					    temp   = V(j,k);
					    V(j,k) = V(j,i);
					    V(j,i) = temp;
				    }
			    }
		    }
      }
      
420
421
422
      std::swap(n,m);
      return true;
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
423
    Matrix() : space(0),n(0),m(0) {}
424
425
426
427
428
429
430
    Matrix(Var * pspace, enumerator pn, enumerator pm) : space(pspace,pspace+pn*pm), n(pn), m(pm) {}
    Matrix(enumerator pn, enumerator pm) : space(pn*pm), n(pn), m(pm) {}
    Matrix(const Matrix & other) : space(other.n*other.m), n(other.n), m(other.m) 
    {
      for(enumerator i = 0; i < n*m; ++i)
        space[i] = other.space[i];
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
431
432
433
434
435
436
437
      template<typename typeB>
      Matrix(const Matrix<typeB> & other) : space(other.Cols()*other.Rows()), n(other.Rows()), m(other.Cols())
      {
          for(enumerator i = 0; i < n; ++i)
              for(enumerator j = 0; j < m; ++j)
                  (*this)(i,j) = get_value(other(i,j));
      }
438
439
440
441
442
443
444
445
446
447
    ~Matrix() {}
    void Resize(enumerator nrows, enumerator mcols)
    {
      if( space.size() != mcols*nrows )
        space.resize(mcols*nrows);
      n = nrows;
      m = mcols;
    }
    Matrix & operator =(Matrix const & other)
    {
Kirill Terekhov's avatar
Kirill Terekhov committed
448
      if( n*m != other.n*other.m ) space.resize(other.n*other.m);
449
450
451
452
453
454
      for(enumerator i = 0; i < other.n*other.m; ++i)
        space[i] = other.space[i];
      n = other.n;
      m = other.m;
      return *this;
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
455
456
457
458
459
460
461
462
463
464
      template<typename typeB>
      Matrix & operator =(Matrix<typeB> const & other)
      {
          if( n*m != other.n*other.m ) space.resize(other.n*other.m);
          for(enumerator i = 0; i < other.n*other.m; ++i)
              space[i] = get_value(other.space[i]);
          n = other.n;
          m = other.m;
          return *this;
      }
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
    // i is in [0,n] - row index
    // j is in [0,m] - column index
    Var & operator()(enumerator i, enumerator j)
    {
      assert(i >= 0 && i < n);
      assert(j >= 0 && j < m);
      assert(i*m+j < n*m); //overflow check?
      return space[i*m+j];
    }
    Var operator()(enumerator i, enumerator j) const
    {
      assert(i >= 0 && i < n);
      assert(j >= 0 && j < m);
      assert(i*m+j < n*m); //overflow check?
      return space[i*m+j];
    }
    Matrix operator-() const
    {
      Matrix ret(n,m);
      for(enumerator k = 0; k < n*m; ++k) ret.space[k] = -space[k];
      return ret;
    }
    template<typename typeB>
    Matrix<typename Promote<Var,typeB>::type> operator-(const Matrix<typeB> & other) const
    {
      assert(Rows() == other.Rows());
      assert(Cols() == other.Cols());
      Matrix<typename Promote<Var,typeB>::type> ret(n,m); //check RVO
Kirill Terekhov's avatar
Kirill Terekhov committed
493
494
495
        for(enumerator i = 0; i < Rows(); ++i)
            for(enumerator j = 0; j < Cols(); ++j)
                ret(i,j) = (*this)(i,j)-other(i,j);
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
      return ret;
    }
    Matrix & operator-=(const Matrix & other)
    {
      assert(n == other.n);
      assert(m == other.m);
      for(enumerator k = 0; k < n*m; ++k) space[k] -= other.space[k];
      return *this;
    }
    template<typename typeB>
    Matrix<typename Promote<Var,typeB>::type> operator+(const Matrix<typeB> & other) const
    {
      assert(Rows() == other.Rows());
      assert(Cols() == other.Cols());
      Matrix<typename Promote<Var,typeB>::type> ret(n,m); //check RVO
Kirill Terekhov's avatar
Kirill Terekhov committed
511
512
513
      for(enumerator i = 0; i < Rows(); ++i)
          for(enumerator j = 0; j < Cols(); ++j)
              ret(i,j) = (*this)(i,j)+other(i,j);
514
515
516
517
518
519
520
521
522
523
524
525
526
      return ret;
    }
    Matrix & operator+=(const Matrix & other)
    {
      assert(n == other.n);
      assert(m == other.m);
      for(enumerator k = 0; k < n*m; ++k) space[k] += other.space[k];
      return *this;
    }
    template<typename typeB>
    Matrix<typename Promote<Var,typeB>::type> operator*(typeB coef) const
    {
      Matrix<typename Promote<Var,typeB>::type> ret(n,m); //check RVO
Kirill Terekhov's avatar
Kirill Terekhov committed
527
528
      for(enumerator i = 0; i < Rows(); ++i)
        for(enumerator j = 0; j < Cols(); ++j) ret(i,j) = (*this)(i,j)*coef;
529
530
531
532
533
534
535
536
537
538
539
      return ret;
    }
    Matrix & operator*=(Var coef)
    {
      for(enumerator k = 0; k < n*m; ++k) space[k] *= coef;
      return *this;
    }
    template<typename typeB>
    Matrix<typename Promote<Var,typeB>::type> operator/(typeB coef) const
    {
      Matrix<typename Promote<Var,typeB>::type> ret(n,m); //check RVO
Kirill Terekhov's avatar
Kirill Terekhov committed
540
541
        for(enumerator i = 0; i < Rows(); ++i)
            for(enumerator j = 0; j < Cols(); ++j) ret(i,j) = (*this)(i,j)/coef;
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
      return ret;
    }
    Matrix & operator/=(Var coef)
    {
      for(enumerator k = 0; k < n*m; ++k) space[k] /= coef;
      return *this;
    }
    template<typename typeB>
    Matrix<typename Promote<Var,typeB>::type> operator*(const Matrix<typeB> & other) const
    {
      assert(Cols() == other.Rows());
      Matrix<typename Promote<Var,typeB>::type> ret(Rows(),other.Cols()); //check RVO
      for(enumerator i = 0; i < Rows(); ++i) //loop rows
      {
        for(enumerator j = 0; j < other.Cols(); ++j) //loop columns
        {
          typename Promote<Var,typeB>::type tmp = 0.0;
          for(enumerator k = 0; k < Cols(); ++k)
            tmp += (*this)(i,k)*other(k,j);
          ret(i,j) = tmp;
        }
      }
      return ret;
    }
    /// performs A*B^{-1}
    /// checks existence of B^{-1} only in debug mode.
    template<typename typeB>
    Matrix<typename Promote<Var,typeB>::type> operator/(const Matrix<typeB> & other) const
    {
      std::pair<Matrix<typeB>,bool> other_inv = other.Invert();
      assert(other_inv.second);
      assert(Cols() == other_inv.Rows());
      Matrix<typename Promote<Var,typeB>::type> ret(n,other.m); //check RVO
      for(enumerator i = 0; i < Rows(); ++i) //loop rows
      {
        for(enumerator j = 0; j < other_inv.Cols(); ++j) //loop columns
        {
          typename Promote<Var,typeB>::type tmp = 0.0;
          for(enumerator k = 0; k < Cols(); ++k)
            tmp += (*this)(i,k)*other_inv.first(k,j);
          ret(i,j) = tmp;
        }
      }
      return ret;
    }
    Matrix Transpose() const
    {
      Matrix ret(m,n);
      for(enumerator i = 0; i < n; ++i)
      {
        for(enumerator j = 0; j < m; ++j)
        {
          ret(j,i) = (*this)(i,j);
        }
      }
      return ret;
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
599
    std::pair<Matrix,bool> Invert(bool print_fail = false) const
600
601
602
    {
      std::pair<Matrix,bool> ret = std::make_pair(Matrix(m,n),true);
      Matrix At = Transpose(); //m by n matrix
Kirill Terekhov's avatar
Kirill Terekhov committed
603
      Matrix AtB = At; //m by n matrix
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
      Matrix AtA = At*(*this); //m by m matrix
      enumerator * order = new enumerator [m];
      for(enumerator i = 0; i < m; ++i) order[i] = i;
      for(enumerator i = 0; i < m; i++)
	    {
		    enumerator maxk = i, maxq = i, temp2;
        Var max, temp;
		    max = fabs(AtA(maxk,maxq));
		    //Find best pivot
        for(enumerator k = i; k < m; k++) // over rows
		    {
			    for(enumerator q = i; q < m; q++) // over columns
			    {
				    if( fabs(AtA(k,q)) > max )
				    {
					    max = fabs(AtA(k,q));
					    maxk = k;
					    maxq = q;
				    }
			    }
		    }
		    //Exchange rows
		    if( maxk != i ) 
		    {
			    for(enumerator q = 0; q < m; q++) // over columns of A
			    {
				    temp = AtA(maxk,q);
				    AtA(maxk,q) = AtA(i,q);
				    AtA(i,q) = temp;
			    }
			    //exchange rhs
			    for(enumerator q = 0; q < n; q++) // over columns of B
			    {
				    temp = AtB(maxk,q);
				    AtB(maxk,q) = AtB(i,q);
				    AtB(i,q) = temp;
			    }
		    }
		    //Exchange columns
		    if( maxq != i ) 
		    {
			    for(enumerator k = 0; k < m; k++) //over rows
			    {
				    temp = AtA(k,maxq);
				    AtA(k,maxq) = AtA(k,i);
				    AtA(k,i) = temp;
			    }
			    //remember order in sol
			    {
				    temp2 = order[maxq];
				    order[maxq] = order[i];
				    order[i] = temp2;
			    }
		    }

		    if( fabs(AtA(i,i)) < 1.0e-54 )
		    {
			    bool ok = true;
			    for(enumerator k = 0; k < n; k++) // over columns of B
			    {
				    if( fabs(AtB(i,k)/1.0e-54) > 1 )
				    {
					    ok = false;
					    break;
				    }
			    }
			    if( ok ) AtA(i,i) = AtA(i,i) < 0.0 ? - 1.0e-12 : 1.0e-12;
			    else
          {
Kirill Terekhov's avatar
Kirill Terekhov committed
673
            if( print_fail ) std::cout << "Failed to invert matrix" << std::endl;
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
            ret.second = false;
            return ret;
          }
		    }
		    for(enumerator k = i+1; k < m; k++)
		    {
			    AtA(i,k) /= AtA(i,i);
			    AtA(k,i) /= AtA(i,i);
		    }
		    for(enumerator k = i+1; k < m; k++)
		    for(enumerator q = i+1; q < m; q++)
		    {
			    AtA(k,q) -= AtA(k,i) * AtA(i,i) * AtA(i,q);
		    }
		    for(enumerator k = 0; k < n; k++)
		    {
			    for(enumerator j = i+1; j < m; j++) //iterate over columns of L
			    {
				    AtB(j,k) -= AtB(i,k) * AtA(j,i);
			    }
			    AtB(i,k) /= AtA(i,i);
		    }
	    }

	    for(enumerator k = 0; k < n; k++)
	    {
		    for(enumerator i = m; i-- > 0; ) //iterate over rows of U
			    for(enumerator j = i+1; j < m; j++) 
			    {
				    AtB(i,k) -= AtB(j,k) * AtA(i,j);
			    }
		    for(enumerator i = 0; i < m; i++)
			    ret.first(order[i],k) = AtB(i,k);
	    }
      delete [] order;
      return ret;
    }
    void Zero()
    {
      for(enumerator i = 0; i < n*m; ++i) space[i] = 0.0;
    }
    Var Trace() const
    {
      assert(n == m);
      Var ret = 0.0;
      for(enumerator i = 0; i < n; ++i) ret += (*this)(i,i);
      return ret;
    }
    Var * data() {return space.data();}
    const Var * data() const {return space.data();}
    enumerator Rows() const {return n;}
    enumerator Cols() const {return m;}
    void Print(INMOST_DATA_REAL_TYPE threshold = 1.0e-10) const
    {
      for(enumerator k = 0; k < n; ++k)
      {
        for(enumerator l = 0; l < m; ++l) 
        {
          if( fabs(get_value((*this)(k,l))) > threshold )
Kirill Terekhov's avatar
Kirill Terekhov committed
733
#if defined(USE_AUTODIFF)
Kirill Terekhov's avatar
Kirill Terekhov committed
734
            std::cout << std::setw(10) << get_value((*this)(k,l));
Kirill Terekhov's avatar
Kirill Terekhov committed
735
736
737
738
#else
            std::cout << std::setw(10) << (*this)(k,l);
#endif
          else
Kirill Terekhov's avatar
Kirill Terekhov committed
739
            std::cout << std::setw(10) << 0;
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
          std::cout << " ";
        }
        std::cout << std::endl;
      }
    }
    bool isSymmetric() const
    {
      if( n != m ) return false;
      for(enumerator k = 0; k < n; ++k)
      {
        for(enumerator l = k+1; l < n; ++l)
          if( fabs((*this)(k,l)-(*this)(l,k)) > 1.0e-7 )
            return false;
      }
      return true;
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
756
757
    template<typename typeB>
    typename Promote<Var,typeB>::type DotProduct(const Matrix<typeB> & other) const
758
759
760
    {
      assert(n == other.n);
      assert(m == other.m);
Kirill Terekhov's avatar
Kirill Terekhov committed
761
762
763
764
      typename Promote<Var,typeB>::type ret = 0.0;
      for(enumerator i = 0; i < n; ++i)
        for(enumerator j = 0; j < m; ++j)
          ret += ((*this)(i,j))*other(i,j);
765
766
      return ret;
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
767
768
769
770
771
      template<typename typeB>
      typename Promote<Var,typeB>::type operator ^(const Matrix<typeB> & other) const
      {
          return DotProduct(other);
      }
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
    Var FrobeniusNorm()
    {
      Var ret = 0;
      for(enumerator i = 0; i < n*m; ++i) ret += space[i]*space[i];
      return sqrt(ret);
    }
    static Matrix<Var> FromTensor(Var * K, enumerator size)
    {
      Matrix<Var> Kc(3,3);
      switch(size)
      {
      case 1: //scalar permeability tensor
        Kc.Zero();
        Kc(0,0) = Kc(1,1) = Kc(2,2) = K[0];
      case 3:
        Kc.Zero(); //diagonal permeability tensor 
        Kc(0,0) = K[0]; //KXX
        Kc(1,1) = K[1]; //KYY
        Kc(2,2) = K[2]; //KZZ
        break;
      case 6: //symmetric permeability tensor
        Kc(0,0) = K[0]; //KXX
        Kc(0,1) = Kc(1,0) = K[1]; //KXY
        Kc(0,2) = Kc(2,0) = K[2]; //KXZ
        Kc(1,1) = K[3]; //KYY
        Kc(1,2) = Kc(2,1) = K[4]; //KYZ
        Kc(2,2) = K[5]; //KZZ
        break;
      case 9: //full permeability tensor
        Kc(0,0) = K[0]; //KXX
        Kc(0,1) = K[1]; //KXY
        Kc(0,2) = K[2]; //KXZ
        Kc(1,0) = K[3]; //KYX
        Kc(1,1) = K[4]; //KYY
        Kc(1,2) = K[5]; //KYZ
        Kc(2,0) = K[6]; //KZX
        Kc(2,1) = K[7]; //KZY
        Kc(2,2) = K[8]; //KZZ
        break;
      }
      return Kc;
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
814
    ///Retrive vector in matrix form from array
815
816
817
818
    static Matrix<Var> FromVector(Var * n, enumerator size)
    {
      return Matrix(n,size,1);
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
819
    ///Create diagonal matrix from array
820
821
822
823
824
825
826
    static Matrix<Var> FromDiagonal(Var * r, enumerator size)
    {
      Matrix ret(size,size);
      ret.Zero();
      for(enumerator k = 0; k < size; ++k) ret(k,k) = r[k];
      return ret;
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
827
    ///Create diagonal matrix from array of inversed values
828
829
830
831
832
833
834
    static Matrix<Var> FromDiagonalInverse(Var * r, enumerator size)
    {
      Matrix ret(size,size);
      ret.Zero();
      for(enumerator k = 0; k < size; ++k) ret(k,k) = 1.0/r[k];
      return ret;
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
	static Matrix CrossProduct(Var vec[3])
	{
		// |  0  -z   y |
		// |  z   0  -x |
		// | -y   x   0 |
		Matrix ret(3,3);
		ret(0,0) = 0.0;
		ret(0,1) = -vec[2]; //-z
		ret(0,2) = vec[1]; //y
		ret(1,0) = vec[2]; //z
		ret(1,1) = 0;
		ret(1,2) = -vec[0]; //-x
		ret(2,0) = -vec[1]; //-y
		ret(2,1) = vec[0]; //x
		ret(2,2) = 0;
		return ret;
	}
Kirill Terekhov's avatar
Kirill Terekhov committed
852
    ///Unit matrix
853
854
855
856
857
858
859
    static Matrix Unit(enumerator pn)
    {
      Matrix ret(pn,pn);
      ret.Zero();
      for(enumerator i = 0; i < pn; ++i) ret(i,i) = 1.0;
      return ret;
    }
Kirill Terekhov's avatar
Kirill Terekhov committed
860
861
862
    /// Concatenate B matrix as columns of current matrix.
    /// Assumes that number of rows of current matrix is
    /// equal to number of rows of B matrix.
Kirill Terekhov's avatar
Kirill Terekhov committed
863
    Matrix ConcatCols(const Matrix & B)
Kirill Terekhov's avatar
Kirill Terekhov committed
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
    {
        assert(Rows() == B.Rows());
        Matrix ret(Rows(),Cols()+B.Cols());
        Matrix & A = *this;
        for(enumerator i = 0; i < Rows(); ++i)
        {
            for(enumerator j = 0; j < Cols(); ++j)
                ret(i,j) = A(i,j);
            for(enumerator j = 0; j < B.Cols(); ++j)
                ret(i,j+Cols()) = B(i,j);
        }
        return ret;
    }
    /// Concatenate B matrix as rows of current matrix.
    /// Assumes that number of colums of current matrix is
    /// equal to number of columns of B matrix.
Kirill Terekhov's avatar
Kirill Terekhov committed
880
    Matrix ConcatRows(const Matrix & B)
Kirill Terekhov's avatar
Kirill Terekhov committed
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
    {
        assert(Cols() == B.Cols());
        Matrix ret(Rows()+B.Rows(),Cols());
        Matrix & A = *this;
        for(enumerator i = 0; i < Rows(); ++i)
        {
            for(enumerator j = 0; j < Cols(); ++j)
                ret(i,j) = A(i,j);
        }
        for(enumerator i = 0; i < B.Rows(); ++i)
        {
            for(enumerator j = 0; j < Cols(); ++j)
                ret(i+Rows(),j) = B(i,j);
        }
        return ret;
    }

    /// Joint diagonalization algorithm by Cardoso
    /// http://perso.telecom-paristech.fr/~cardoso/Algo/Joint_Diag/joint_diag_r.m
    /// Current matrix should have size n by n*m
    /// And represent concatination of m n by n matrices
Kirill Terekhov's avatar
Kirill Terekhov committed
902
    Matrix JointDiagonalization(INMOST_DATA_REAL_TYPE threshold = 1.0e-7)
Kirill Terekhov's avatar
Kirill Terekhov committed
903
    {
Kirill Terekhov's avatar
Kirill Terekhov committed
904
905
        enumerator N = Rows();
        enumerator M = Cols() / Rows();
Kirill Terekhov's avatar
Kirill Terekhov committed
906
        Matrix V = Matrix::Unit(m);
Kirill Terekhov's avatar
Kirill Terekhov committed
907
        Matrix R(2,M);
Kirill Terekhov's avatar
Kirill Terekhov committed
908
909
910
911
912
913
914
        Matrix G(2,2);
        Matrix & A = *this;
        Var ton, toff, theta, c, s, Ap, Aq, Vp, Vq;
        bool repeat;
        do
        {
            repeat = false;
Kirill Terekhov's avatar
Kirill Terekhov committed
915
            for(enumerator p = 0; p < N-1; ++p)
Kirill Terekhov's avatar
Kirill Terekhov committed
916
            {
Kirill Terekhov's avatar
Kirill Terekhov committed
917
                for(enumerator q = p+1; q < N; ++q)
Kirill Terekhov's avatar
Kirill Terekhov committed
918
                {
Kirill Terekhov's avatar
Kirill Terekhov committed
919
                    for(enumerator k = 0; k < M; ++k)
Kirill Terekhov's avatar
Kirill Terekhov committed
920
                    {
Kirill Terekhov's avatar
Kirill Terekhov committed
921
922
                        R(0,k) = A(p,p + k*N) - A(q,q + k*N);
                        R(1,k) = A(p,q + k*N) + A(q,p + k*N);
Kirill Terekhov's avatar
Kirill Terekhov committed
923
924
925
926
927
928
929
930
931
                    }
                    G = R*R.Transpose();
                    Var ton  = G(0,0) - G(1,1);
                    Var toff = G(0,1) + G(1,0);
                    Var theta = 0.5 * atan2( toff, ton + sqrt(ton*ton + toff*toff) );
                    Var c = cos(theta);
                    Var s = sin(theta);
                    if( fabs(s) > threshold )
                    {
Kirill Terekhov's avatar
Kirill Terekhov committed
932
933
934
                        //std::cout << "p,q: " << p << "," << q << " c,s: " << c << "," << s << std::endl;
                        repeat = true;
                        for(enumerator k = 0; k < M; ++k)
Kirill Terekhov's avatar
Kirill Terekhov committed
935
                        {
Kirill Terekhov's avatar
Kirill Terekhov committed
936
                            for(enumerator i = 0; i < N; ++i)
Kirill Terekhov's avatar
Kirill Terekhov committed
937
                            {
Kirill Terekhov's avatar
Kirill Terekhov committed
938
939
940
941
                                Ap = A(i,p + k*N);
                                Aq = A(i,q + k*N);
                                A(i,p + k*N) = Ap*c + Aq*s;
                                A(i,q + k*N) = Aq*c - Ap*s;
Kirill Terekhov's avatar
Kirill Terekhov committed
942
943
                            }
                        }
Kirill Terekhov's avatar
Kirill Terekhov committed
944
                        for(enumerator k = 0; k < M; ++k)
Kirill Terekhov's avatar
Kirill Terekhov committed
945
                        {
Kirill Terekhov's avatar
Kirill Terekhov committed
946
                            for(enumerator j = 0; j < N; ++j)
Kirill Terekhov's avatar
Kirill Terekhov committed
947
                            {
Kirill Terekhov's avatar
Kirill Terekhov committed
948
949
950
951
                                Ap = A(p,j + k*N);
                                Aq = A(q,j + k*N);
                                A(p,j + k*N) = Ap*c + Aq*s;
                                A(q,j + k*N) = Aq*c - Ap*s;
Kirill Terekhov's avatar
Kirill Terekhov committed
952
953
                            }
                        }
Kirill Terekhov's avatar
Kirill Terekhov committed
954
                        for(enumerator i = 0; i < N; ++i)
Kirill Terekhov's avatar
Kirill Terekhov committed
955
956
957
958
                        {
                            Vp = V(i,p);
                            Vq = V(i,q);
                            V(i,p) = Vp*c + Vq*s;
Kirill Terekhov's avatar
Kirill Terekhov committed
959
                            V(i,q) = Vq*c - Vp*s;
Kirill Terekhov's avatar
Kirill Terekhov committed
960
961
962
963
                        }
                    }
                }
            }
Kirill Terekhov's avatar
Kirill Terekhov committed
964
            //Print();
Kirill Terekhov's avatar
Kirill Terekhov committed
965
966
967
968
        } while( repeat );
        return V;
    }

969
  };
Kirill Terekhov's avatar
Kirill Terekhov committed
970
    
Kirill Terekhov's avatar
Kirill Terekhov committed
971
972
973
974
975
976
977
978
979
    template<typename typeB>
    Matrix<typename Promote<INMOST_DATA_REAL_TYPE,typeB>::type> operator *(INMOST_DATA_REAL_TYPE coef, const Matrix<typeB> & other)
    {return other*coef;}
	
#if defined(USE_AUTODIFF)
	template<typename typeB>
	Matrix<typename Promote<variable,typeB>::type> operator *(const variable & coef, const Matrix<typeB> & other)
	{return other*coef;}
#endif
980
981
982
983
984
985
986
987
988
989


  typedef Matrix<INMOST_DATA_REAL_TYPE> rMatrix; //shortcut for real matrix
#if defined(USE_AUTODIFF)
  typedef Matrix<variable> vMatrix; //shortcut for matrix with variations
#endif
}


#endif //INMOST_DENSE_INCLUDED