/************************************************************************* * * * Vega FEM Simulation Library Version 3.1 * * * * "sparseMatrix" library , Copyright (C) 2007 CMU, 2009 MIT, 2016 USC * * All rights reserved. * * * * Code author: Jernej Barbic * * http://www.jernejbarbic.com/code * * * * Research: Jernej Barbic, Fun Shing Sin, Daniel Schroeder, * * Doug L. James, Jovan Popovic * * * * Funding: National Science Foundation, Link Foundation, * * Singapore-MIT GAMBIT Game Lab, * * Zumberge Research and Innovation Fund at USC * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the BSD-style license that is * * included with this library in the file LICENSE.txt * * * * This library 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 file * * LICENSE.TXT for more details. * * * *************************************************************************/ #include #include #include #include #include #include "sparseMatrix.h" using namespace std; SparseMatrixOutline::SparseMatrixOutline(int numRows_): numRows(numRows_) { Allocate(); } SparseMatrixOutline::~SparseMatrixOutline() { // deallocate column entries for(int i=0; i entry; for(int i=0; i entry; for(int i=0; i::iterator pos = columnEntries[i].find(j); if (pos != columnEntries[i].end()) pos->second += value; else { pair entry(j,value); columnEntries[i].insert(entry); } } // remove the entry in row i, column j void SparseMatrixOutline::RemoveEntry(int i, int j) { assert((size_t)i <= columnEntries.size()); columnEntries[i].erase(j); } // add a block matrix, starting at row i, and column j void SparseMatrixOutline::AddBlockMatrix(int iStart, int jStart, const SparseMatrix * block, double scalarFactor) { int nBlock = block->GetNumRows(); for(int i=0; iGetRowLength(i); for(int j=0; jGetColumnIndex(i,j), scalarFactor * block->GetEntry(i,j)); } } void SparseMatrixOutline::MultiplyRow(int row, double scalar) { for(map::iterator iter = columnEntries[row].begin(); iter != columnEntries[row].end(); iter++) iter->second *= scalar; } void SparseMatrixOutline::AddBlock3x3Entry(int i, int j, const double * matrix3x3) { for(int k=0; k<3; k++) for(int l=0; l<3; l++) AddEntry(3*i+k,3*j+l,matrix3x3[3*k+l]); } void SparseMatrixOutline::AddBlock3x3Entry(int i, int j, double value) { for(int k=0; k<3; k++) for(int l=0; l<3; l++) AddEntry(3*i+k,3*j+l,value); } double SparseMatrixOutline::GetEntry(int i, int j) const { map::const_iterator pos = columnEntries[i].find(j); if (pos != columnEntries[i].end()) return (pos->second); else return 0; } int SparseMatrixOutline::GetNumColumns() const { int numColumns = -1; for(int i=0; i::const_iterator j1; // traverse all row entries for(j1=columnEntries[i].begin(); j1 != columnEntries[i].end(); j1++) if (j1->first > numColumns) numColumns = j1->first; } return numColumns + 1; } int SparseMatrixOutline::Save(const char * filename, int oneIndexed) const { FILE * fout = fopen(filename, "w"); if (!fout) return 1; fprintf(fout, "%d\n%d\n", numRows, GetNumColumns()); for(int i=0; i::const_iterator j1; // traverse all row entries for(j1=columnEntries[i].begin(); j1 != columnEntries[i].end(); ++j1) fprintf(fout,"%d %d %.15f\n",i,j1->first + oneIndexed, j1->second + oneIndexed); } fclose(fout); return 0; } void SparseMatrixOutline::Print() const { for (int i=0; iGetNumRows(); Allocate(); for(int i=0; icolumnEntries[i].size()); columnIndices[i] = (int*) malloc (sizeof(int) * rowLength[i]); columnEntries[i] = (double*) malloc (sizeof(double) * rowLength[i]); map::iterator pos; int j = 0; int prev = -1; for(pos = sparseMatrixOutline->columnEntries[i].begin(); pos != sparseMatrixOutline->columnEntries[i].end(); pos++) { columnIndices[i][j] = pos->first; if (columnIndices[i][j] <= prev) printf("Warning: entries not sorted in a row in a sparse matrix.\n"); prev = columnIndices[i][j]; columnEntries[i][j] = pos->second; j++; } } } // construct matrix 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 SparseMatrix::SparseMatrix(int numRows_, int * rowLength_, int ** columnIndices_, double ** columnEntries_, int shallowCopy) : numRows(numRows_) { if (shallowCopy) { rowLength = rowLength_; columnIndices = columnIndices_; columnEntries = columnEntries_; numSubMatrixIDs = 0; subMatrixIndices = NULL; subMatrixIndexLengths = NULL; subMatrixStartRow = NULL; subMatrixNumRows = NULL; superMatrixIndices = NULL; superRows = NULL; diagonalIndices = NULL; transposedIndices = NULL; return; } Allocate(); for (int i = 0; i=0; i--) FreeSubMatrixIndices(i); } if (superRows != NULL) { for(int i=0; icolumnEntries[i][j] = columnEntries[i][j] * alpha; } void SparseMatrix::ScalarMultiplyAdd(const double alpha, SparseMatrix * dest) { if (dest == NULL) dest = this; for(int i=0; icolumnEntries[i][j] += columnEntries[i][j] * alpha; } void SparseMatrix::ResetToZero() { for(int i=0; i maxEntry) maxEntry = fabs(entry1 + entry2); } } return maxEntry; } void SparseMatrix::SymmetrizeMatrix() { BuildTranspositionIndices(); for(int i=0; i= i) break; // copy elt (jAbs,i) into position (i,jAbs) columnEntries[i][j] = columnEntries[jAbs][TransposedIndex(i,j)]; } } } double SparseMatrix::GetMaxAbsEntry() const { double max = 0; for(int i=0; i max) max = el; } } return max; } double SparseMatrix::GetRowNorm2(int row) const { double norm2 = 0; for(int j=0; j= nSuper) || (nextSuperDOF < 0) ) { printf("Error: invalid fixed super DOF %d specified.\n", nextSuperDOF); exit(1); } while (superDOF < nextSuperDOF) { if (constrainedDOF >= nConstrained) { printf("Error: too many DOFs specified.\n"); exit(1); } (*superDOFs)[constrainedDOF] = superDOF; constrainedDOF++; superDOF++; } superDOF++; // skip the deselected DOF } while (superDOF < nSuper) { if (constrainedDOF >= nConstrained) { printf("Error: too many DOFs specified.\n"); exit(1); } (*superDOFs)[constrainedDOF] = superDOF; constrainedDOF++; superDOF++; } } void SparseMatrix::BuildSuperMatrixIndices(int numFixedRowColumns, int * fixedRowColumns, const SparseMatrix * superMatrix, int oneIndexed) { BuildSuperMatrixIndices(numFixedRowColumns, fixedRowColumns, numFixedRowColumns, fixedRowColumns, superMatrix, oneIndexed); } void SparseMatrix::BuildSuperMatrixIndices(int numFixedRows, int * fixedRows, int numFixedColumns, int * fixedColumns, const SparseMatrix * superMatrix, int oneIndexed) { int numSuperColumns = superMatrix->GetNumColumns(); int numColumns = numSuperColumns - numFixedColumns; if ((numRows + numFixedRows != superMatrix->numRows) || (GetNumColumns() + numFixedColumns > numSuperColumns) ) { printf("Error in BuildSuperMatrixIndices: number of constrained DOFs does not match the size of the two matrices.\n"); printf("num rows: %d num fixed rows in super matrix: %d num rows in super matrix: %d\n", numRows, numFixedRows, superMatrix->numRows); printf("num columns: %d num fixed columns in super matrix: %d num columns in super matrix: %d\n", numColumns, numFixedColumns, numSuperColumns); exit(1); } // build row renumbering function: BuildRenumberingVector(numRows, superMatrix->numRows, numFixedRows, fixedRows, &superRows, oneIndexed); // build column renumbering function: int * superColumns_; BuildRenumberingVector(numColumns, numSuperColumns, numFixedColumns, fixedColumns, &superColumns_, oneIndexed); // superRows[i] is the row index in the super matrix corresponsing to row i of constrained matrix // superColumns_[i] is the dense column index in the super matrix corresponsing to the dense column i of constrained matrix // build column indices superMatrixIndices = (int**) malloc (sizeof(int*) * numRows); for(int i=0; i < numRows; i++) { superMatrixIndices[i] = (int*) malloc (sizeof(int) * rowLength[i]); for(int j=0; j < rowLength[i]; j++) { int iConstrained = i; int jConstrainedDense = columnIndices[iConstrained][j]; int iSuper = superRows[iConstrained]; int jSuperDense = superColumns_[jConstrainedDense]; int jSuper = superMatrix->GetInverseIndex(iSuper, jSuperDense); if (jSuper < 0) { printf("Error in BuildSuperMatrixIndices: failed to compute inverse index.\n"); printf("i=%d j=%d iConstrained=%d jConstrainedDense=%d iSuper=%d jSuperDense=%d jSuper=%d\n", i, j, iConstrained, jConstrainedDense, iSuper, jSuperDense, jSuper); fflush(NULL); exit(1); } superMatrixIndices[i][j] = jSuper; } } free(superColumns_); } void SparseMatrix::AssignSuperMatrix(const SparseMatrix & superMatrix) { for(int i=0; i= numSubMatrixIDs) { subMatrixIndices = (int***) realloc (subMatrixIndices, sizeof(int**) * (subMatrixID + 1)); subMatrixIndexLengths = (int**) realloc (subMatrixIndexLengths, sizeof(int*) * (subMatrixID + 1)); subMatrixStartRow = (int*) realloc(subMatrixStartRow, sizeof(int) * (subMatrixID + 1)); subMatrixNumRows = (int*) realloc(subMatrixNumRows, sizeof(int) * (subMatrixID + 1)); for(int i=numSubMatrixIDs; i <= subMatrixID; i++) { subMatrixIndices[i] = NULL; subMatrixIndexLengths[i] = NULL; subMatrixStartRow[i] = 0; subMatrixNumRows[i] = 0; } numSubMatrixIDs = subMatrixID + 1; } else if ((subMatrixIndices[subMatrixID] != NULL) || (subMatrixIndexLengths[subMatrixID] != NULL)) { free(subMatrixIndices[subMatrixID]); free(subMatrixIndexLengths[subMatrixID]); subMatrixIndices[subMatrixID] = NULL; subMatrixIndexLengths[subMatrixID] = NULL; subMatrixStartRow[subMatrixID] = 0; subMatrixNumRows[subMatrixID] = 0; //printf("Warning: old submatrix indices (matrixID %d) have not been de-allocated.\n", subMatrixID); } subMatrixStartRow[subMatrixID] = startRow; subMatrixNumRows[subMatrixID] = submatrix.numRows; subMatrixIndices[subMatrixID] = (int**) malloc (sizeof(int*) * subMatrixNumRows[subMatrixID]); subMatrixIndexLengths[subMatrixID] = (int*) malloc (sizeof(int) * subMatrixNumRows[subMatrixID]); int endRow = startRow + subMatrixNumRows[subMatrixID]; if(endRow > numRows) { printf("Error (BuildSubMatrixIndices): given submatrix placed at startRow %d exceeds the length of this matrix: %d\n", startRow, numRows); exit(1); } for(int i=0; i= numSubMatrixIDs) { printf("Warning: attempted to free submatrix index that does not exist.\n"); return; } if (subMatrixIndices[subMatrixID] != NULL) { for(int i=0; i=0; i--) { if (subMatrixIndices[i] != NULL) { numSubMatrixIDs = i + 1; subMatrixIndices = (int***) realloc (subMatrixIndices, sizeof(int**) * numSubMatrixIDs); subMatrixIndexLengths = (int**) realloc (subMatrixIndexLengths, sizeof(int*) * numSubMatrixIDs); subMatrixStartRow = (int*) realloc (subMatrixStartRow, sizeof(int) * numSubMatrixIDs); subMatrixNumRows = (int*) realloc (subMatrixNumRows, sizeof(int) * numSubMatrixIDs); break; } numSubMatrixIDs = i; } if (numSubMatrixIDs == 0) { free(subMatrixIndices); free(subMatrixIndexLengths); free(subMatrixStartRow); free(subMatrixNumRows); subMatrixIndices = NULL; subMatrixIndexLengths = NULL; subMatrixStartRow = NULL; subMatrixNumRows = NULL; } } void SparseMatrix::AssignSubMatrix(const SparseMatrix & submatrix, int subMatrixID) { int startRow = subMatrixStartRow[subMatrixID]; for(int i=0; i= i) num++; } } return num; } int SparseMatrix::GenerateNAGFormat(double * a, int * irow, int * icol, int * istr) const { int num = 0; for(int i=0; i= row)) { if (a != NULL) a[count] = columnEntries[row][j]; if (ja != NULL) ja[count] = columnIndices[row][j] + oneIndexed; count++; } } } if (ia != NULL) ia[numRows] = count + oneIndexed; } void SparseMatrix::GenerateCompressedRowMajorFormat_four_array(double * values, int * columns, int * pointerB, int * pointerE, int upperTriangleOnly, int oneIndexed) const { int count = 0; for(int row=0; row= row)) { if (values != NULL) values[count] = columnEntries[row][j]; if (columns != NULL) columns[count] = columnIndices[row][j] + oneIndexed; count++; } } if (pointerE != NULL) pointerE[row] = count + oneIndexed; } } int SparseMatrix::Save(const char * filename, int oneIndexed) const { FILE * fout = fopen(filename,"w"); if (!fout) return 1; fprintf(fout,"%d\n%d\n", numRows, GetNumColumns()); for(int i=0; i index) { // decrease index columnIndices[i][j]--; } } } numRows--; } void SparseMatrix::RemoveRowsColumnsSlow(int numRemovedRowsColumns, const int * removedRowsColumns, int oneIndexed) { for(int i=0; i oldToNew(numRows); int dof = 0; int dofCount = 0; for(int i=0; i index) { // decrease index columnIndices[i][j]--; } } } } void SparseMatrix::RemoveColumns(int numRemovedColumns, const int * removedColumns, int oneIndexed) { // the removed dofs must be pre-sorted // build a map from old dofs to new ones int numColumns = GetNumColumns(); // must increase numColumns to accommodate matrices with zero columns on the right for(int i=0; i numColumns) numColumns = neededNumColumns; } vector oldToNew(numColumns); int dof = 0; int dofCount = 0; for(int i=0; i oldToNew(numRows); int dof = 0; int dofCount = 0; for(int i=0; i norm) norm = absRowSum; } return norm; } double SparseMatrix::GetFrobeniusNorm() const { double sum = 0.0; for(int i=0; i inftyNorm) inftyNorm = fabs(buffer[i] - b[i]); if (fabs(b[i]) > inftyNorm_b) inftyNorm_b = fabs(b[i]); } if (verbose) { printf("Infinity residual norm ||Ax-b|| is %G. ||b|| is %G.\n", inftyNorm, inftyNorm_b); printf("Relative infinity residual norm ||Ax-b||/||b|| is %G.\n", inftyNorm / inftyNorm_b); } free(bufferv); return inftyNorm / inftyNorm_b; } void SparseMatrix::MakeDenseMatrix(double * denseMatrix, int numColumns) const { if (numColumns == -1) numColumns = GetNumColumns(); memset(denseMatrix, 0, sizeof(double) * (numRows * numColumns)); for(int i=0; i< numRows; i++) for(int j=0; j numColumns) numColumns = columnIndices[i][j]; } } return numColumns + 1; } void SparseMatrix::IncreaseNumRows(int numAddedRows) { int newn = numRows + numAddedRows; rowLength = (int*) realloc (rowLength, sizeof(int) * newn); for(int i=0; i, pair > fourTuple; typedef vector listOfFourTuples; typedef map rowMap; vector rowMaps; for(int i=0; isecond).push_back(tuple); } } } } // copy map to precomputedIndices (*precomputedIndices) = (int***) malloc (sizeof(int**) * MTilde.numRows); for(int i=0; isecond).size()) + 1)); ((*precomputedIndices)[i][j])[0] = (int)((iter->second).size()); for(int k=0; k<((*precomputedIndices)[i][j])[0]; k++) { ((*precomputedIndices)[i][j])[1+4*k+0] = ((iter->second)[k]).first.first; ((*precomputedIndices)[i][j])[1+4*k+1] = ((iter->second)[k]).first.second; ((*precomputedIndices)[i][j])[1+4*k+2] = ((iter->second)[k]).second.first; ((*precomputedIndices)[i][j])[1+4*k+3] = ((iter->second)[k]).second.second; } j++; } } } void SparseMatrix::ConjugateMatrix(precomputedIndicesType precomputedIndices, SparseMatrix & U, SparseMatrix & MTilde) { MTilde.ResetToZero(); for(int row=0; rowGetNumRows(); i++) { int row = startRow + i; if (row >= numRows) return; rowLength[row] = source->GetRowLength(i); columnIndices[row] = (int*) realloc (columnIndices[row], sizeof(int) * rowLength[row]); columnEntries[row] = (double*) realloc (columnEntries[row], sizeof(double) * rowLength[row]); for(int j=0; jcolumnIndices[i][j]; columnEntries[row][j] = source->columnEntries[i][j]; } } } void SparseMatrix::AppendRowsColumns(const SparseMatrix * source) { int * oldRowLengths = (int*) malloc (sizeof(int) * numRows); for(int i=0; iGetNumRows()); SetRows(source, oldNumRows); // add transpose of rows: // first, establish new column lengths for(int row=0; rowGetNumRows(); row++) { for(int j=0; jGetRowLength(row); j++) { int column = source->GetColumnIndex(row, j); rowLength[column]++; } } // extend size for(int row=0; rowGetNumRows(); row++) { for(int j=0; jGetRowLength(row); j++) { int column = source->GetColumnIndex(row, j); columnIndices[column][rowLength[column]] = oldNumRows + row; columnEntries[column][rowLength[column]] = source->GetEntry(row, j); rowLength[column]++; } } free(oldRowLengths); // append zero diagonal in lower-right block (helps with some solvers, such as PARDISO) for(int row=0; rowGetNumRows(); row++) { rowLength[oldNumRows + row]++; columnIndices[oldNumRows + row] = (int*) realloc (columnIndices[oldNumRows + row], sizeof(int) * rowLength[oldNumRows + row]); columnEntries[oldNumRows + row] = (double*) realloc (columnEntries[oldNumRows + row], sizeof(double) * rowLength[oldNumRows + row]); columnIndices[oldNumRows + row][rowLength[oldNumRows + row] - 1] = oldNumRows + row; columnEntries[oldNumRows + row][rowLength[oldNumRows + row] - 1] = 0.0; } } SparseMatrix * SparseMatrix::CreateIdentityMatrix(int numRows) { SparseMatrixOutline * outline = new SparseMatrixOutline(numRows); for (int row=0; rowAddEntry(row, row, 1.0); SparseMatrix * mat = new SparseMatrix(outline); delete outline; return mat; }