| 1 |
// Author: David Alexander |
| 2 |
|
| 3 |
#include <algorithm> |
| 4 |
#include <boost/tuple/tuple.hpp> |
| 5 |
#include <limits> |
| 6 |
#include <vector> |
| 7 |
|
| 8 |
#include <ConsensusCore/Matrix/SparseMatrix.hpp> |
| 9 |
|
| 10 |
namespace ConsensusCore { |
| 11 |
// Performance insensitive routines are not inlined |
| 12 |
|
| 13 |
SparseMatrix::SparseMatrix(int rows, int cols) |
| 14 |
: columns_(cols) |
| 15 |
, nCols_(cols) |
| 16 |
, nRows_(rows) |
| 17 |
, columnBeingEdited_(-1) |
| 18 |
, usedRanges_(cols, Interval(0, 0)) |
| 19 |
{ |
| 20 |
for (int j = 0; j < nCols_; j++) { |
| 21 |
columns_[j] = NULL; |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
SparseMatrix::SparseMatrix(const SparseMatrix& other) |
| 26 |
: columns_(other.nCols_) |
| 27 |
, nCols_(other.nCols_) |
| 28 |
, nRows_(other.nRows_) |
| 29 |
, columnBeingEdited_(other.columnBeingEdited_) |
| 30 |
, usedRanges_(other.usedRanges_) |
| 31 |
{ |
| 32 |
for (int j = 0; j < nCols_; j++) { |
| 33 |
if (other.columns_[j] != NULL) { |
| 34 |
columns_[j] = new SparseVector(*other.columns_[j]); |
| 35 |
} else { |
| 36 |
columns_[j] = NULL; |
| 37 |
} |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
SparseMatrix::~SparseMatrix() |
| 42 |
{ |
| 43 |
for (int j = 0; j < nCols_; j++) { |
| 44 |
if (columns_[j] != NULL) delete columns_[j]; |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
int SparseMatrix::UsedEntries() const |
| 49 |
{ |
| 50 |
// use column ranges |
| 51 |
int filledEntries = 0; |
| 52 |
for (int col = 0; col < Columns(); ++col) { |
| 53 |
int start, end; |
| 54 |
boost::tie(start, end) = UsedRowRange(col); |
| 55 |
filledEntries += (end - start); |
| 56 |
} |
| 57 |
return filledEntries; |
| 58 |
} |
| 59 |
|
| 60 |
int SparseMatrix::AllocatedEntries() const |
| 61 |
{ |
| 62 |
int sum = 0; |
| 63 |
for (int j = 0; j < nCols_; j++) { |
| 64 |
sum += (columns_[j] != NULL ? columns_[j]->AllocatedEntries() : 0); |
| 65 |
} |
| 66 |
return sum; |
| 67 |
} |
| 68 |
|
| 69 |
void SparseMatrix::ToHostMatrix(float** mat, int* rows, int* cols) const |
| 70 |
{ |
| 71 |
const float nan = std::numeric_limits<float>::quiet_NaN(); |
| 72 |
*mat = new float[Rows() * Columns()]; |
| 73 |
*rows = Rows(); |
| 74 |
*cols = Columns(); |
| 75 |
for (int i = 0; i < Rows(); i++) { |
| 76 |
for (int j = 0; j < Columns(); j++) { |
| 77 |
(*mat)[i * Columns() + j] = IsAllocated(i, j) ? Get(i, j) : nan; |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
void SparseMatrix::CheckInvariants(int) const |
| 83 |
{ |
| 84 |
for (int j = 0; j < nCols_; j++) { |
| 85 |
if (columns_[j] != NULL) columns_[j]->CheckInvariants(); |
| 86 |
} |
| 87 |
} |
| 88 |
} |