Debian Codegraph @

tools/physicalModeling/mesh2faust/vega/libraries/include/sparseMatrix.h

raw symbols SCIP
1 /*************************************************************************
2 * *
3 * Vega FEM Simulation Library Version 3.1 *
4 * *
5 * "sparseMatrix" library , Copyright (C) 2007 CMU, 2009 MIT, 2016 USC *
6 * All rights reserved. *
7 * *
8 * Code author: Jernej Barbic *
9 * http://www.jernejbarbic.com/code *
10 * *
11 * Research: Jernej Barbic, Fun Shing Sin, Daniel Schroeder, *
12 * Doug L. James, Jovan Popovic *
13 * *
14 * Funding: National Science Foundation, Link Foundation, *
15 * Singapore-MIT GAMBIT Game Lab, *
16 * Zumberge Research and Innovation Fund at USC *
17 * *
18 * This library is free software; you can redistribute it and/or *
19 * modify it under the terms of the BSD-style license that is *
20 * included with this library in the file LICENSE.txt *
21 * *
22 * This library is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file *
25 * LICENSE.TXT for more details. *
26 * *
27 *************************************************************************/
28
29 #ifndef _SPARSE_MATRIX_H_
30 #define _SPARSE_MATRIX_H_
31
32 /*
33 The "SparseMatrix" class implements double-precision sparse matrices
34 with common algebraic operations such as incremental construction,
35 addition, mtx-vec multiplication, row-column deletion.
36 The matrices can be loaded from and saved to a file.
37
38 The matrix can be rectangular (it need not be square).
39 In memory, the matrix is stored in a row-based format.
40 For each matrix row, the class stores the integer
41 indices of the columns containing non-zero entries,
42 together with the corresponding double precision values.
43 All quantities (rows, columns, etc.) in this class are 0-indexed.
44
45 Also included is a Conjugate Gradient iterative linear system solver
46 (for positive-definite large sparse symmetric matrices).
47 The solver can be used without preconditioning, or with diagonal (Jacobi) preconditoning.
48 The solver either uses an explicitly provided sparse matrix, or you can only
49 provide the matrix-vector multiplication routine (without explicitly giving the matrix).
50 The CG Solver was implemented by following Jonathan Shewchuk's
51 "An Introduction to the Conjugate Gradient Method Without the Agonizing Pain":
52 http://www.cs.cmu.edu/~jrs/jrspapers.html#cg
53
54 The class also includes a Gauss-Seidel iterative linear system solver.
55
56 There are two classes available to the user: SparseMatrixOutline and SparseMatrix.
57 The SparseMatrixOutline class should be used to construct the non-zero
58 locations in the matrix, and (optionally) assign values to them.
59 You should then transform it into a SparseMatrix class, via SparseMatrix's
60 class constructor. The SparseMatrix class has all the computational routines,
61 but you can only add new non-zero entries to SparseMatrixOutline, not
62 to SparseMatrix. The reason for this separation is that SparseMatrixOutline
63 does not know the number of matrix entries ahead of time, so it uses STL's
64 "map" datastructure to store the matrix data. In the SparseMatrix class, however, the number
65 of sparse entries and their locations are fixed, so all operations can use
66 known-length C arrays, which is faster.
67
68 So: you should first create an instance of SparseMatrixOutline, then create
69 an instance of SparseMatrix by passing the SparseMatrixOutline object to
70 SparseMatrix's constructor.
71 If your matrix is a text file on disk, you can load it to SparseMatrixOutline,
72 or directly load it into SparseMatrix (which will, however, internally still
73 proceed via SparseMatrixOutline).
74
75 The text disk file format is as follows:
76 <number of matrix rows>
77 <number of matrix columns>
78 one or more data lines, each giving one matrix entry, in the format:
79 <row index> <column index> <data value>
80 (indices are 0-indexed)
81
82 Example:
83
84 [0 17 -1 0]
85 A=[0 5 0 0]
86 [3 8 6 0]
87
88 would be given as:
89
90 3
91 4
92 0 1 17
93 0 2 -1
94 1 1 5
95 2 0 3
96 2 1 8
97 2 2 6
98 */
99
100 #include <string.h>
101 #include <vector>
102 #include <map>
103
104 class SparseMatrix;
105
106 class SparseMatrixOutline
107 {
108 public:
109 // makes an empty sparse matrix with numRows rows
110 SparseMatrixOutline(int numRows);
111 ~SparseMatrixOutline();
112
113 // makes a diagonal numRows x numRows sparse matrix; with a constant diagonal
114 SparseMatrixOutline(int numRows, double diagonal);
115 // makes a diagonal numRows x numRows sparse matrix; diagonal is a vector of n numbers
116 SparseMatrixOutline(int numRows, double * diagonal);
117
118 // loads the sparse matrix from a text file
119 // if expand is greater than 1, the routine also expands each element into a diagonal block of size expand x expand...
120 // (expand option is useful for loading the mass matrix in structural mechanics (with expand=3 in 3D))
121 SparseMatrixOutline(const char * filename, int expand=1);
122
123 // save matrix to a text file
124 int Save(const char * filename, int oneIndexed=0) const;
125
126 // add entry at location (i,j) in the matrix
127 void AddEntry(int i, int j, double value=0.0);
128 // remove entry at location (i,j)
129 void RemoveEntry(int i, int j);
130 // add a 3x3 matrix at location (3*i, 3*j)
131 void AddBlock3x3Entry(int i, int j, const double * matrix3x3); // matrix3x3 should be given in row-major order
132 void AddBlock3x3Entry(int i, int j, double value=0.0); // matrix is assigned the value at all 3x3 elements
133 // add a block (sparse) matrix (optionally multiplied with "scalarFactor"), starting at row i, and column j
134 void AddBlockMatrix(int i, int j, const SparseMatrix * block, double scalarFactor=1.0);
135 void IncreaseNumRows(int numAddedRows); // increases the number of matrix rows (new rows are added at the bottom of the matrix, and are all empty)
136
137 void MultiplyRow(int row, double scalar); // multiplies all elements in row 'row' with scalar 'scalar'
138
139 inline int Getn() const { return numRows; } // get number of rows
140 inline int GetNumRows() const { return numRows; } // get number of rows
141 int GetNumColumns() const; // get the number of columns (i.e., search for max column index)
142 int GetNumEntries() const; // get total number of non-zero matrix elements
143 double GetEntry(int i, int j) const; // returns the matrix entry at location (i,j) in the matrix (or zero if entry has not been assigned)
144 void Print() const;
145
146 // low-level routine which is rarely used
147 inline const std::map<int,double> & GetRow(int i) const { return columnEntries[i]; }
148 friend class SparseMatrix;
149
150 protected:
151 int numRows;
152 std::vector< std::map<int,double> > columnEntries;
153 void Allocate();
154 };
155
156 class SparseMatrix
157 {
158 public:
159
160 SparseMatrix(const char * filename); // load from text file (same text file format as SparseMatrixOutline)
161 SparseMatrix(SparseMatrixOutline * sparseMatrixOutline); // create it from the outline
162 // create it by specifying all entries: number of rows, length of each row, indices of columns of non-zero entries in each row, values of non-zero entries in each row
163 // column indices in each row must be sorted (ascending)
164 // if shallowCopy=1, the class will not allocate its own internal buffers, but will assume ownership of the input rowLength, columnIndices and columnEntries parameters
165 SparseMatrix(int numRows, int * rowLength, int ** columnIndices, double ** columnEntries, int shallowCopy=0);
166
167 SparseMatrix(const SparseMatrix & source); // copy constructor
168 ~SparseMatrix();
169
170 int Save(const char * filename, int oneIndexed=0) const; // save matrix to a disk text file
171
172 int SaveToMatlabFormat(const char * filename) const; // save matrix to a text file that can be imported into Matlab
173
174 // set/add value to the j-th sparse entry in the given row (NOT to matrix element at (row,j))
175 inline void SetEntry(int row, int j, double value) { columnEntries[row][j] = value; }
176 inline void AddEntry(int row, int j, double value) { columnEntries[row][j] += value; }
177 void ResetToZero(); // reset all entries to zero
178 void ResetRowToZero(int row); // reset all entries in the row to zero
179
180 inline int Getn() const { return numRows; } // get the number of rows
181 inline int GetNumRows() const { return numRows; }
182 inline int GetRowLength(int row) const { return rowLength[row]; }
183 int GetNumColumns() const; // get the number of columns (i.e., search for max column index)
184 // returns the j-th sparse entry in row i (NOT matrix element at (row, j))
185 inline double GetEntry(int row, int j) const { return columnEntries[row][j]; }
186 // returns the column index of the j-th sparse entry in the given row
187 inline int GetColumnIndex(int row, int j) const { return columnIndices[row][j]; }
188 inline double ** GetEntries() const { return columnEntries; }
189 inline int ** GetColumnIndices() const { return columnIndices; }
190 inline int * GetRowLengths() const { return rowLength; }
191
192 // finds the compressed column index of element at location (row, jDense)
193 // returns -1 if column not found
194 int GetInverseIndex(int row, int jDense) const;
195
196 int GetNumEntries() const; // returns the total number of non-zero entries
197 double SumEntries() const; // returns the sum of all matrix entries
198 void SumRowEntries(double * rowSums) const; // returns the sum of all entries in each row
199 double GetMaxAbsEntry() const; // max abs value of a matrix entry
200 double GetInfinityNorm() const; // matrix infinity norm: maximum absolute row sum of the matrix
201 double GetFrobeniusNorm() const; // matrix Frobenius norm: sqrt of the sum of absolute squares of its elements
202 void Print(int sparsePrint=0) const; // prints the matrix out to standard output
203 double GetRowNorm2(int row) const;
204
205 // matrix algebra (all involved matrices must have the same pattern of non-zero entries)
206 SparseMatrix operator+(const SparseMatrix & mat2) const;
207 SparseMatrix operator-(const SparseMatrix & mat2) const;
208 friend SparseMatrix operator* (const double alpha, const SparseMatrix & mat2); // warning: this function makes a local copy; "ScalarMultiply" is more efficient
209 SparseMatrix & operator=(const SparseMatrix & source); // matrices must have same size and locations of non-zero entries
210 SparseMatrix & operator*=(const double alpha);
211 SparseMatrix & operator+=(const SparseMatrix & mat2);
212 SparseMatrix & operator-=(const SparseMatrix & mat2);
213 bool operator==(const SparseMatrix & mat2) const;
214 // check whether two sparse matrices share the same size and locations of non-zero entries
215 bool SameStructure(const SparseMatrix & mat2) const;
216
217 void ScalarMultiply(const double alpha, SparseMatrix * dest=NULL); // dest = alpha * dest (if dest=NULL, operation is applied to this object)
218 void ScalarMultiplyAdd(const double alpha, SparseMatrix * dest=NULL); // dest += alpha * dest (if dest=NULL, operation is applied to this object)
219 void MultiplyRow(int row, double scalar); // multiplies all elements in row 'row' with scalar 'scalar'
220
221 // multiplies the sparse matrix with the given vector/matrix
222 void MultiplyVector(const double * vector, double * result) const; // result = A * vector
223 void MultiplyVectorAdd(const double * vector, double * result) const; // result += A * vector
224 void MultiplyVector(int startRow, int endRow, const double * vector, double * result) const; // result = A(startRow:endRow-1,:) * vector
225 void TransposeMultiplyVector(const double * vector, int resultLength, double * result) const; // result = trans(A) * vector
226 void TransposeMultiplyVectorAdd(const double * vector, double * result) const; // result += trans(A) * vector
227 void MultiplyMatrix(int numDenseRows, int numDenseColumns, const double * denseMatrix, double * result) const; // result = A * denseMatrix (denseMatrix is a numDenseRows x numDenseColumns dense matrix, result is a numRows x numDenseColumns dense matrix)
228 void MultiplyMatrixAdd(int numDenseRows, int numDenseColumns, const double * denseMatrix, double * result) const; // result += A * denseMatrix (denseMatrix is a numDenseRows x numDenseColumns dense matrix, result is a numDenseRows x numDenseColumns dense matrix)
229 void MultiplyMatrixTranspose(int numDenseColumns, const double * denseMatrix, double * result) const; // result = A * trans(denseMatrix) (trans(denseMatrix) is a dense matrix with 'numDenseColumns' columns, result is a numRows x numDenseColumns dense matrix)
230
231 // computes <M * vector, vector> (assumes symmetric M)
232 double QuadraticForm(const double * vector) const;
233 // normalizes vector in the M-norm: vector := vector / sqrt(<M * vector, vector>) (assumes symmetric M)
234 void NormalizeVector(double * vector) const;
235 void ConjugateMatrix(const double * U, int r, double * MTilde) const; // computes MTilde = U^T M U (M can be a general square matrix, U need not be a square matrix; number of columns of U is r; sizes of M and U must be such that product is defined; output matrix will have size r x r, stored column-major)
236 SparseMatrix ConjugateMatrix(SparseMatrix & U, int verbose=0, int numColumns=-1); // computes U^T M U (M is this matrix, and can be a general square matrix, U need not be a square matrix; sizes of M and U must be such that product is defined); numColumns is the number of columns of the result (U^T M U); this is important because there could be empty columns in U at the right border of the U matrix; if numColumns=-1, the routine will use U->GetNumColumns()
237
238 // builds indices for subsequent faster product computation (below)
239 // input: U, MTilde; MTilde must equal U^T M U, computed using the "ConjugateMatrix" routine above
240 // output: precomputedIndices
241 typedef int *** precomputedIndicesType;
242 void BuildConjugationIndices(SparseMatrix & U, SparseMatrix & MTilde, precomputedIndicesType * precomputedIndices); // note: must be debugged
243 // input: precomputedIndices, U
244 // output: MTilde
245 void ConjugateMatrix(precomputedIndicesType precomputedIndices, SparseMatrix & U, SparseMatrix & MTilde); // note: must be debugged
246
247 // writes all entries into the space provided by 'data'
248 // space must be pre-allocated
249 // data is written row after row, and by non-zero columns within each row
250 void MakeLinearDataArray(double * data) const;
251 // writes row indices of non-zero entries into array "indices"
252 // same order as for data
253 void MakeLinearRowIndexArray(int * indices) const;
254 // indices in this function version are double to ensure compatibility with Matlab
255 void MakeLinearRowIndexArray(double * indices) const;
256 // writes column indices
257 void MakeLinearColumnIndexArray(int * indices) const;
258 void MakeLinearColumnIndexArray(double * indices) const;
259
260 // Make a dense matrix (column-major storage).
261 // (this can be a huge matrix for large sparse matrices)
262 // Storage in denseMatrix must be pre-allocated.
263 // The size of the denseMatrix is: this->GetNumRows() x (numColumns == -1 ? this->GetNumColumns() : numColumns).
264 void MakeDenseMatrix(double * denseMatrix, int numColumns=-1) const;
265 // also transposes the matrix:
266 void MakeDenseMatrixTranspose(int numColumns, double * denseMatrix) const;
267
268 // removes row(s) and column(s) from the matrix
269 void RemoveRowColumn(int rowColumn); // 0-indexed
270 void RemoveRowsColumns(int numRemovedRowColumns, const int * removedRowColumns, int oneIndexed=0); // the rowColumns must be sorted (ascending)
271 void RemoveRowsColumnsSlow(int numRemovedRowColumns, const int * removedRowColumns, int oneIndexed=0); // the rowColumns need not be sorted
272
273 // removes row(s) from the matrix
274 void RemoveRow(int row); // 0-indexed
275 void RemoveRows(int numRemovedRows, const int * removedRows, int oneIndexed=0); // rows must be sorted (ascending)
276 void RemoveRowsSlow(int numRemovedRows, const int * removedRows, int oneIndexed=0); // the rows need not be sorted
277
278 // removes column(s) from the matrix
279 void RemoveColumn(int column); // 0-indexed
280 void RemoveColumns(int numRemovedColumns, const int * removedColumns, int oneIndexed=0); // columns must be sorted (ascending)
281 void RemoveColumnsSlow(int numRemovedColumns, const int * removedColumns, int oneIndexed=0); // columns need not be sorted
282
283 void IncreaseNumRows(int numAddedRows); // increases the number of matrix rows (new rows are added at the bottom of the matrix, and are all empty)
284 void SetRows(const SparseMatrix * source, int startRow, int startColumn=0); // starting with startRow, overwrites the rows with those of matrix "source"; data is written into columns starting at startColumn
285 void AppendRowsColumns(const SparseMatrix * source); // appends the matrix "source" at the bottom of matrix, and trans(source) to the right of the matrix
286
287 // transposition (note: the matrix need not be symmetric)
288 void BuildTranspositionIndices();
289 void FreeTranspositionIndices();
290 // returns the list position of the transposed element (row, list position j)
291 // must first call BuildTranspositionIndices()
292 inline int TransposedIndex(int row, int j) const { return transposedIndices[row][j]; }
293
294 // returns the transposed matrix
295 // numColumns is the number of columns in the original matrix;
296 // this is important in case there are zero columns at the end of the matrix
297 // if numColumns=-1 (default), GetNumColumns() will be called; however, this will lead to a transposed matrix with a fewer number of rows in case of empty columns at the end of the original matrix
298 SparseMatrix * Transpose(int numColumns=-1);
299 // assign a transposed matrix AT to this matrix; topology of AT must be transpose of topology of this matrix
300 // note: this function calls BuildTranspositionIndices internally, so you don't need to call BuildTranspositionIndices first
301 void AssignTransposedMatrix(SparseMatrix & AT);
302
303 // checks if the matrix is skew-symmetric
304 // the non-zero entry locations must form a symmetric pattern
305 // returns max ( abs ( A^T + A ) ) = || A^T + A ||_{\infty}
306 // note: this function calls BuildTranspositionIndices internally, so you don't need to call BuildTranspositionIndices first
307 double SkewSymmetricCheck();
308 // makes matrix symmetric by copying upper triangle + diagonal into the lower triangle
309 // the non-zero entry locations must form a symmetric pattern
310 // note: this function calls BuildTranspositionIndices internally, so you don't need to call BuildTranspositionIndices first
311 void SymmetrizeMatrix();
312
313 // pre-computes the sparse columns of diagonal matrix entries
314 // this routine will accelerate subsequent GetDiagonal or AddDiagonalMatrix calls, but is not necessary for GetDiagonal or AddDiagonalMatrix
315 void BuildDiagonalIndices();
316 void FreeDiagonalIndices();
317 void GetDiagonal(double * diagonal) const;
318 void AddDiagonalMatrix(double * diagonalMatrix);
319 void AddDiagonalMatrix(double constDiagonalElement);
320
321 // Build submatrix indices is used for pair of matrices where the sparsity of one matrix is a subset of another matrix (for example, mass matrix and stiffness matrix).
322 // It allows you to assign/add a submatrix to the current matrix.
323 // The submatrix begins at row "startRow" and column "startColumn" of this matrix.
324 // submatrixID allows you to keep several submatrices at once
325 // Call this once to establish the correspondence:
326 void BuildSubMatrixIndices(const SparseMatrix & submatrix, int subMatrixID=0, int startRow=0, int startColumn=0);
327 void FreeSubMatrixIndices(int subMatrixID=0);
328 // assign a submatrix to the current matrix, whose elements are a subset of the elements of the current matrix
329 // note: the other entries of the current matrix are unmodified
330 void AssignSubMatrix(const SparseMatrix & submatrix, int subMatrixID=0);
331 // assign the current matrix to a submatrix
332 void AssignToSubMatrix(SparseMatrix & submatrix, int subMatrixID=0) const;
333 // add a matrix to the current matrix, whose elements are a subset of the elements of the current matrix
334 // += factor * mat2
335 // returns *this
336 SparseMatrix & AddSubMatrix(double factor, SparseMatrix & submatrix, int subMatrixID=0);
337
338 // Build supermatrix indices is used for pair of matrices with rows/columns removed.
339 // It allows you to assign a super matrix to the current matrix.
340 // oneIndexed: tells whether the fixed rows and columns are specified 1-indexed or 0-indexed
341 // First, call BuildSuperMatrixIndices once to inialize (all fixed rows and columns are indexed with respect the superMatrix):
342 void BuildSuperMatrixIndices(int numFixedRowColumns, int * fixedRowColumns, const SparseMatrix * superMatrix, int oneIndexed=0); // use this version if the indices of removed rows and columns are the same
343 void BuildSuperMatrixIndices(int numFixedRows, int * fixedRows, int numFixedColumns, int * fixedColumns, const SparseMatrix * superMatrix, int oneIndexed=0); // allows arbitrary row and column indices
344 // Then, call this (potentially many times) to quickly assign the values at the appropriate places in the submatrix.
345 // For example, you can use this to copy data from a matrix into a submatrix obtained by a previous call to RemoveRowColumns.
346 void AssignSuperMatrix(const SparseMatrix & superMatrix);
347
348 // returns the total number of non-zero entries in the lower triangle (including diagonal)
349 int GetNumLowerTriangleEntries() const;
350 int GetNumUpperTriangleEntries() const;
351 // exports the matrix to format for NAG library
352 int GenerateNAGFormat(double * a,int * irow,int * icol, int * istr) const;
353
354 void GenerateCompressedRowMajorFormat(double * a, int * ia, int * ja, int upperTriangleOnly=0, int oneIndexed=0) const;
355 void GenerateCompressedRowMajorFormat_four_array(double * values, int * columns, int * pointerB, int * pointerE, int upperTriangleOnly=0, int oneIndexed=0) const;
356
357 // diagonal solve M * x = b
358 // ASSUMES the sparse matrix is diagonal !
359 // result is overwritten into rhs
360 // (to solve non-diagonal linear systems, you need to use an external library; or you can use the CGSolver class, or you can use the Gauss-Seidel iteration below)
361 void DiagonalSolve(double * rhs) const;
362
363 // performs one Gauss-Seidel iteration of solving the system A * x = b
364 // updates vector x in place, b is not modified
365 // (A can be a general matrix)
366 // assumes that diagonal entries of the matrix are set and are non-zero
367 void DoOneGaussSeidelIteration(double * x, const double * b) const;
368 void ComputeResidual(const double * x, const double * b, double * residual) const;
369 // checks if A * x - b is close to zero and prints out the findings
370 // returns ||A * x - b|| / ||b|| (all norms are infinity)
371 // passing a buffer (length of n) will avoid a malloc/free pair to generate scratch space for the residual
372 double CheckLinearSystemSolution(const double * x, const double * b, int verbose=1, double * buffer=NULL) const;
373
374 // below are low-level routines which are rarely used
375 inline double ** GetDataHandle() const { return columnEntries; }
376 inline double * GetRowHandle(int row) const { return columnEntries[row]; }
377
378 // create a nxn identity matrix
379 static SparseMatrix * CreateIdentityMatrix(int n);
380
381 protected:
382
383 // compressed row storage
384 int numRows; // number of rows
385 int * rowLength; // length of each row
386 int ** columnIndices; // indices of columns of non-zero entries in each row
387 double ** columnEntries; // values of non-zero entries in each row
388
389 int * diagonalIndices;
390 int ** transposedIndices;
391
392 /*
393 numSubMatrixIDs specifies how many sub-matrix relationships we have
394 length(subMatrixIndices) == length(subMatrixIndexLengths) == length(subMatrixStartRow) == (numSubMatrixIDs + 1)
395 length(subMatrixIndexLengths[subMatrixID]) == length(subMatrixIndices[subMatrixID]) == number of rows = numRows
396 length(subMatrixIndices[subMatrixID][rowIndex]) == subMatrixIndexLengths[subMatrixID][rowIndex]
397 */
398 int numSubMatrixIDs;
399 int *** subMatrixIndices;
400 int ** subMatrixIndexLengths;
401 int * subMatrixStartRow;
402 int * subMatrixNumRows;
403
404 int ** superMatrixIndices;
405 int * superRows;
406
407 void InitFromOutline(SparseMatrixOutline * sparseMatrixOutline);
408 void Allocate();
409 void BuildRenumberingVector(int nConstrained, int nSuper, int numFixedDOFs, int * fixedDOFs, int ** superDOFs, int oneIndexed=0);
410 };
411
412 #endif
413