Debian Codegraph @

tools/physicalModeling/mesh2faust/vega/libraries/matrix/matrix.h

raw symbols SCIP
1 /*************************************************************************
2 * *
3 * Vega FEM Simulation Library Version 3.1 *
4 * *
5 * "matrix" library , Copyright (C) 2007 CMU, 2009 MIT *
6 * All rights reserved. *
7 * *
8 * Code author: Jernej Barbic *
9 * http://www.jernejbarbic.com/code *
10 * Research: Jernej Barbic, Doug L. James, Jovan Popovic *
11 * Funding: NSF, Link Foundation, Singapore-MIT GAMBIT Game Lab *
12 * *
13 * This library is free software; you can redistribute it and/or *
14 * modify it under the terms of the BSD-style license that is *
15 * included with this library in the file LICENSE.txt *
16 * *
17 * This library is distributed in the hope that it will be useful, *
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file *
20 * LICENSE.TXT for more details. *
21 * *
22 *************************************************************************/
23
24 /*
25 The "Matrix" class implements a matrix: a 2D array of real values,
26 together with the commonly defined algebraic operations.
27 The matrix can be rectangular (they need not be necessarily square).
28 The matrix is stored in the column-major order (same as in LAPACK).
29 Storage is dense (see the "sparseMatrix" library for sparse matrices).
30 The class suports common algebraic operations (addition, multiplication,
31 transposition, etc.), including operator overloading, so you can
32 write expressions like: A += 0.25 * (B + A) * C;
33 It is possible to load/save the matrix from/to a file, using
34 a special well-documented binary format (see matrixIO.h).
35 The class can also perform more complex matrix operations such
36 as computing the SVD decomposition, solving linear systems (via LU decomposition),
37 finding eigenvalues and eigenvectors, solving least square systems, and
38 computing matrix inverses and pseudoinverses.
39 The code uses BLAS routines to perform matrix addition and multiplication,
40 and LAPACK for SVD, LU, eigenanalysis, least square systems, inverses and pseudoinverses.
41
42 The code can use the expokit package (http://www.maths.uq.edu.au/expokit/) to compute matrix exponentials. The wrapper to expokit is implemented ("MExpv" and "MExp" routines), but it is disabled by default to avoid linking problems when not using expokit. See the comment at the MExpv routine below for how to enable the exp functionality. Also note that the MExp and MExpv routines only work in double precision. This is because expokit supports double precision matrix exponentials (DGPADM), but does not currently include a single-precision routine SGPADM.
43
44 */
45
46 #ifndef _MATRIX_H_
47 #define _MATRIX_H_
48
49 #include <stdlib.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include "matrixMacros.h"
53 #include "matrixBLAS.h"
54 #include "matrixLAPACK.h"
55
56 // uncomment the following to use the MExpv and MExp routines:
57 //#define USE_EXPOKIT
58
59 #ifdef USE_EXPOKIT
60 #include "matrixExp.h"
61 #endif
62
63 template<class real>
64 class Matrix
65 {
66 public:
67 // load matrix from a file (see matrixIO.h for the binary file format)
68 Matrix(const char * filename);
69
70 // create a m x n matrix; "data" must an array of length m*n, giving the matrix entries in column-major order
71 // if "makeInternalDataCopy" is true (default), the class will internally make a copy of the data; otherwise, it will only direct its internal pointer to the user-provided array data
72 // if "freeDataInDestructor" is true (default), the class will free the data array in the destructor; if "makeInternalDataCopy" is false, you will typically want to set "freeDataInDestructor" to false too
73 Matrix(int m, int n, const real * data,
74 bool makeInternalDataCopy = true, bool freeDataInDestructor = true);
75 // create a m x n matrix of all zeros
76 Matrix (int m, int n, bool freeDataInDestructor = true);
77 // create a m x n matrix of constant entries
78 Matrix (int m, int n, real constEntry, bool freeDataInDestructor = true);
79 // create a m x m diagonal matrix with all the diagonal entries equaling "diagonal"
80 Matrix (int m, real diagonal, bool freeDataInDestructor = true);
81 // create a m x m diagonal matrix with the diagonal entries specified by the array diagonal (of length m)
82 Matrix (int m, const real * diagonal, bool freeDataInDestructor = true);
83 // create a m x m diagonal matrix with the diagonal entries specified by the m x 1 matrix "vec"
84 Matrix (int m, const Matrix & vec, bool freeDataInDestructor = true);
85 Matrix(const Matrix & mtx2);
86 ~Matrix();
87
88 inline int Getm() const { return m; }
89 inline int Getn() const { return n; }
90 inline real * GetData() const { return data; }
91
92 const Matrix operator+ (const Matrix & mtx2) const;
93 const Matrix operator- (const Matrix & mtx2) const;
94 const Matrix operator* (const Matrix & mtx2) const;
95 Matrix & operator= (const Matrix & mtx2);
96 Matrix & operator+= (const Matrix & mtx2);
97 Matrix & operator-= (const Matrix & mtx2);
98 Matrix & operator*= (const Matrix & mtx2);
99 Matrix & operator*= (const real alpha);
100 inline const real & operator() (int row, int columns) const;
101 inline real & operator() (int row, int columns);
102
103 // output = trans(this) * mtx2
104 const Matrix MultiplyT (const Matrix & mtx2) const;
105
106 // transpose the matrix in place, i.e., without creating an intermediate copy buffer (useful with large matrices where the copy might otherwise not fit into memory)
107 Matrix & InPlaceTranspose();
108
109 // sets the submatrix, defined by its upper-left corner at (i,j) and the dimensions of "submatrix", to entries from the matrix "submatrix"
110 void SetSubmatrix(int i, int j, const Matrix<real> & submatrix);
111
112 void RemoveRows(int rowStart, int rowEnd);
113 void RemoveColumns(int columnStart, int columnEnd);
114 void RemoveRowsColumns(int columnStart, int columnEnd);
115 void AppendRows(const Matrix<real> & rows);
116 void AppendColumns(const Matrix<real> & columns);
117 void AppendRowsColumns(const Matrix<real> & bottomLeftBlock, const Matrix<real> & topRightBlock, const Matrix<real> & bottomRightBlock);
118
119 real MaxAbsEntry() const;
120
121 void Print(int numDigits=-1) const; // if numDigits=-1: use %G flag
122 int Save(const char * filename) const; // returns 0 on success, 1 on failure
123
124 // factor <this matrix> = Q * Lambda * Q^T
125 // matrix must be symmetric (no checks performed)
126 // Lambda will be returned as a n x 1 vector, in ascending order
127 void SymmetricEigenDecomposition(Matrix<real> & Q, Matrix<real> & Lambda);
128
129 // computes SVD of matrix
130 // this matrix = U * diag(Sigma) * VT
131 // note: Sigma is returned as a MIN(m,n) x 1 vector
132 // U must be a m x MIN(m,n) matrix
133 // VT must be a MIN(m,n) x n matrix
134 void SVD(Matrix<real> & U, Matrix<real> & Sigma, Matrix<real> & VT);
135
136 // compute eigenvalues and eigenvectors of a general matrix
137 // eigenvectors are returned in the n x n matrix EigenVectors
138 // eigenvalues are (in general) complex and are returned in n x 1 vectors LambdaRe and LambdaIm
139 // return value: 0 on success, xGEEV INFO on failure (a general matrix is not always diagonalizable)
140 int EigenDecomposition(Matrix<real> & EigenVectors, Matrix<real> & LambdaRe, Matrix<real> & LambdaIm);
141
142 // solves linear system (via LU):
143 // (this matrix) * x = rhs
144 int LUSolve(const Matrix<real> & x, const Matrix<real> & rhs);
145
146 // scalar-matrix multiplication
147 // example: A = 0.37 * B;
148 inline friend const Matrix<real> operator* (real alpha, const Matrix<real> & mtx2)
149 {
150 real * output = ScalarMultiplyMatrix(mtx2.Getm(), mtx2.Getn(), alpha,mtx2.GetData());
151 return Matrix<real>(mtx2.Getm(),mtx2.Getn(),output,false);
152 }
153
154 // compute the Frobenius inner product of two matrices (sum of products of all pairwise entries)
155 // example: double product = FrobeniusInnerProduct(A, B);
156 inline friend real FrobeniusInnerProduct(const Matrix<real> & mtx1, const Matrix<real> & mtx2)
157 {
158 if ((mtx1.Getm() != mtx2.Getm()) || (mtx1.Getn() != mtx2.Getn()))
159 {
160 printf("Matrix size mismatch in Matrix::FrobeniusInnerProduct.\n");
161 throw 10;
162 }
163 real product = 0.0;
164 int mn = mtx1.Getm() * mtx1.Getn();
165 for(int i=0; i<mn; i++)
166 product += mtx1.data[i] * mtx2.data[i];
167 return product;
168 }
169
170 // transpose the matrix
171 // example: A = Transpose(B);
172 inline friend const Matrix<real> Transpose(const Matrix<real> & mtx2)
173 {
174 real * buffer = (real*) malloc (sizeof(real) * mtx2.Getm() * mtx2.Getn());
175 memcpy(buffer, mtx2.GetData(), sizeof(real) * mtx2.Getm() * mtx2.Getn());
176 InPlaceTransposeMatrix(mtx2.Getm(), mtx2.Getn(), buffer);
177 return Matrix<real>(mtx2.Getn(), mtx2.Getm(), buffer, false);
178 }
179
180 // compute matrix inverse
181 // example: A = Inverse(B);
182 inline friend const Matrix<real> Inverse(const Matrix<real> & mtx2)
183 {
184 if (mtx2.Getm() != mtx2.Getn())
185 {
186 printf("Matrix size mismatch in Matrix::Inverse . mtx2.m = %d, mtx2.n = %d\n", mtx2.Getm(), mtx2.Getn());
187 throw 11;
188 }
189 real * buffer = InverseMatrix(mtx2.Getm(), mtx2.GetData());
190 return Matrix<real>(mtx2.Getm(), mtx2.Getm(), buffer, false);
191 }
192
193 // compute matrix pseudoinverse
194 // example: A = PseudoInverse(B);
195 inline friend const Matrix<real> PseudoInverse(const Matrix<real> & mtx2, real singularValueThreshold, int * rank)
196 {
197 real * buffer = PseudoInverseMatrix(mtx2.Getm(), mtx2.Getn(),
198 mtx2.GetData(), singularValueThreshold, rank);
199 return Matrix<real>(mtx2.Getn(), mtx2.Getm(), buffer, false);
200 }
201
202 // solve the least square system: mtx * output = rhs
203 // rcond is the condition number beyond which matrix singular values are considered singular (see also LAPACK)
204 // rank is a pointer to a single integer, giving the non-singular rank of the matrix, based on rcond
205 // example: A * X = B
206 // int rank;
207 // X = LeastSquareSolve(A, B, 1e-12, &rank);
208 inline friend const Matrix<real> LeastSquareSolve(const Matrix<real> & mtx, const Matrix<real> & rhs, real rcond, int * rank)
209 {
210 if (mtx.Getm() != rhs.Getm())
211 {
212 printf("Matrix size mismatch in Matrix::LeastSquareSolve . mtx.m = %d, rhs.m = %d\n", mtx.Getm(), rhs.Getm());
213 throw 12;
214 }
215 real * buffer = MatrixLeastSquareSolve(mtx.Getm(), mtx.Getn(), rhs.Getn(),
216 mtx.GetData(), rhs.GetData(), rcond, rank);
217 return Matrix<real>(mtx.Getn(), rhs.Getn(), buffer, false);
218 }
219
220 // === matrix exponential routines ===
221
222 // In order to use these routines, you must enable the USE_EXPOKIT definition in the header of matrix.h (disabled by default to avoid linker problems when expokit is not used), and link your code against the expokit library:
223 // http://www.maths.uq.edu.au/expokit/
224 // The expokit routines compute the matrix exponential of a general matrix in
225 // full, using the irreducible rational Pade approximation to the
226 // exponential function exp(x) = r(x) = (+/-)( I + 2*(q(x)/p(x)) ),
227 // combined with scaling-and-squaring.
228
229 // computes w = exp((this matrix)*t)v, where v and w are vectors, and t is a scalar
230 // "this matrix" must be a square matrix (denote the dimensions by m x m)
231 // v and w are m x 1 vectors
232 // note: this routine uses the same algorithm as MExp below: it explicitly constructs exp((this matrix)*t), and then multiplies by v
233 void MExpv(real t, const Matrix<real> & v, Matrix<real> & w);
234
235 // computes A = exp(t*mtx), where A and mtx are square matrices, and t is a scalar
236 // code is a pointer to an integer where the xgpasm expokit routine exit code will be stored (you can pass NULL to discard this code); normal termination is code 0
237 inline friend const Matrix<real> MExp(real t, const Matrix<real> & mtx, int * code = NULL)
238 {
239 #ifdef USE_EXPOKIT
240 if (mtx.Getm() != mtx.Getn())
241 {
242 printf("Matrix size mismatch in Matrix::MExp . mtx.m = %d, mtx.n = %d\n", mtx.Getm(), mtx.Getn());
243 throw 13;
244 }
245
246 real * buffer = (real*) malloc (sizeof(real) * mtx.Getm() * mtx.Getm());
247 int codei = MatrixExp(mtx.Getm(), mtx.GetData(), t, buffer);
248 if (code != NULL)
249 *code = codei;
250 return Matrix<real>(mtx.Getm(), mtx.Getm(), buffer, false);
251 #else
252 printf("Error: MExp is not enabled.\n");
253 return Matrix<real>();
254 #endif
255 }
256
257 protected:
258 int m, n;
259 real * data;
260 bool freeDataInDestructor;
261 };
262
263 template<class real>
264 inline const real & Matrix<real>::operator() (int row, int column) const
265 {
266 return data[ELT(m,row,column)];
267 }
268
269 template<class real>
270 inline real & Matrix<real>::operator() (int row, int column)
271 {
272 return data[ELT(m,row,column)];
273 }
274
275 #endif
276