Code Documentation 3.7
Social Network Visualizer
Loading...
Searching...
No Matches
matrix.h
Go to the documentation of this file.
1
15
16
17#ifndef MATRIX_H
18#define MATRIX_H
19
20#include <QtGlobal>
21#include <QString> //for static const QString declares below
22#include <functional> // std::function, for the optional cancelCheck callback
23#include <utility> // std::pair, std::make_pair
24#include <vector>
25
26using namespace std; //or else compiler groans for nothrow
27
28class QTextStream;
29
30
31#ifdef Q_OS_WIN32
32static const QString infinity = "\u221E" ;
33#else
34static const QString infinity = QString("\xE2\x88\x9E") ;
35#endif
36
37
38static const int METRIC_NONE = -1;
39static const int METRIC_SIMPLE_MATCHING = 0;
40static const int METRIC_JACCARD_INDEX = 1;
41static const int METRIC_HAMMING_DISTANCE = 2;
42static const int METRIC_COSINE_SIMILARITY = 3;
43static const int METRIC_EUCLIDEAN_DISTANCE = 4;
44static const int METRIC_MANHATTAN_DISTANCE= 5;
45static const int METRIC_PEARSON_COEFFICIENT = 6;
46static const int METRIC_CHEBYSHEV_MAXIMUM= 7;
47
48
69
70
71class Matrix {
72public:
74 Matrix (int rowDim=0, int colDim=0) ;
75
76 Matrix(const Matrix &b) ; /* Copy constructor allows Matrix a=b */
77
78 ~Matrix();
79
80 void clear();
81
82 void resize (const int m, const int n) ;
83
84 // m_rowPtr[r] is the address of row r's first cell inside m_data (see rebuildRowPtr()
85 // below). So m_rowPtr[r][c] is: fetch that address, then step c cells forward.
86 qreal item( int r, int c ) { return m_rowPtr[r][c]; }
87
88 void setItem(const int r, const int c, const qreal elem ) { m_rowPtr[r][c] = elem; }
89
90 // Returns a raw pointer to the start of row r, so a[i][j] indexing keeps working
91 // for ludcmp()/lubksb()/inverse() without a wrapper row type.
92 qreal* operator [] (const int &r) { return m_rowPtr[r]; }
93
94 void clearItem( int r, int c ) { m_rowPtr[r][c] = 0; }
95
96 int cols() {return m_cols;}
97
98 int rows() {return m_rows;}
99
100 int size() { return m_rows * m_cols; }
101
102 void findMinMaxValues(qreal&min, qreal&max, bool &hasRealNumbers);
103
104 void NeighboursNearestFarthest(qreal&min,qreal&max,
105 int &imin, int &jmin,
106 int &imax, int &jmax);
107
108 void deleteRowColumn(int i); /* deletes row i and column i */
109
110 void identityMatrix (int dim);
111
112 void zeroMatrix (const int m, const int n);
113
114 void fillMatrix (qreal value );
115
117
118
120
121 void sum(Matrix &a, Matrix &b) ;
122
123 void operator +=(Matrix & b);
124
126
128
130 void operator *=(Matrix & b);
131
132 void product( Matrix &A, Matrix & B, bool symmetry=false) ;
133
134 Matrix & productSym( Matrix &a, Matrix & b) ;
135
136 void swapRows(int rowA,int rowB);
137
138 void multiplyScalar(const qreal &f);
139 void multiplyRow(int row, qreal value);
140
141 void productByVector (
142 qreal in[],
143 qreal out[],
144 const bool &leftMultiply=false);
145
146 Matrix & pow (int n, bool symmetry=false) ;
147 Matrix & expBySquaring2 (Matrix &Y, Matrix &X, int n, bool symmetry=false);
148
149 qreal distanceManhattan(
150 qreal x[],
151 qreal y[],
152 int n);
153 qreal distanceEuclidean(
154 qreal x[],
155 int n);
156
157 void powerIteration (
158 qreal x[] ,
159 qreal &xsum,
160 qreal &xmax,
161 int &xmaxi,
162 qreal &xmin,
163 int &xmini,
164 const qreal eps, const int &maxIter,
165 std::function<bool()> cancelCheck = nullptr,
166 qreal *lambdaMax = nullptr);
167
169
171
172 Matrix& transpose();
173
175
176
178
179 bool inverse(Matrix &a, std::function<bool()> cancelCheck = nullptr);
180
181 bool solve(qreal b[]);
182
183 bool ludcmp (Matrix &a, const int &n, int indx[], qreal &d, std::function<bool()> cancelCheck = nullptr) ;
184
185 void lubksb (Matrix &a, const int &n, int indx[], qreal b[]);
186
187
188 Matrix& distancesMatrix(const int &metric,
189 const QString varLocation,
190 const bool &diagonal,
191 const bool &considerWeights,
192 std::function<bool()> cancelCheck = nullptr);
193
195 const int &measure,
196 const QString varLocation="Rows",
197 const bool &diagonal=false,
198 const bool &considerWeights=true,
199 std::function<bool()> cancelCheck = nullptr);
200
201
203 const QString &varLocation="Rows",
204 const bool &diagonal=false,
205 std::function<bool()> cancelCheck = nullptr);
206
207
208 friend QTextStream& operator << (QTextStream& os, Matrix& m);
209 bool printHTMLTable(QTextStream& os,
210 const bool markDiag=false,
211 const bool &plain=false,
212 const bool &printInfinity=true);
213 bool printMatrixConsole(bool debug=true);
214
215 bool illDefined();
216
217private:
218 // Builds m_rowPtr[]: a lookup table of row-start pointers into m_data, one entry per
219 // row, so item()/setItem()/operator[] never have to recompute a row's address from
220 // scratch. Concretely: m_rowPtr is an array of m_rows pointers; entry r is set to
221 // "m_data, advanced by r whole rows" (r*m_cols cells). Looking up cell (r,c) then
222 // becomes "read m_rowPtr[r] to get row r's address, then step c cells forward from
223 // it" - one array read plus one cheap offset, regardless of how large the matrix is,
224 // versus recomputing r*m_cols (a real multiplication) on every single access.
225 //
226 // Must be called once after every place that gives m_data a new address or a new
227 // m_cols - the constructor, the copy constructor, resize(), identityMatrix(),
228 // zeroMatrix(), deleteRowColumn(), and the branch of operator=() that reallocates -
229 // because every entry in the old m_rowPtr[] would otherwise point at stale memory or
230 // use the wrong row width. Complexity: O(m_rows) - one pointer computed per row, not
231 // per cell, which is what keeps this cheap even for large matrices.
232 //
233 // This function only allocates and fills; it does not free a previous m_rowPtr array.
234 // Callers that already have one from an earlier allocation must free it themselves
235 // first (via clear(), or a direct delete[] - see deleteRowColumn()) before calling this.
237 m_rowPtr = new (nothrow) qreal*[m_rows];
238 Q_CHECK_PTR( m_rowPtr );
239 for (int i=0; i<m_rows; i++) {
240 m_rowPtr[i] = m_data + static_cast<size_t>(i) * m_cols;
241 }
242 }
243
244 qreal *m_data; // the actual N*M cells, one allocation, row-major.
245 qreal **m_rowPtr; // m_rowPtr[r] == m_data + r*m_cols, precomputed for every row.
248
249};
250
251
252
253
254
255#endif
General-purpose dense matrix (adjacency, distance, similarity, sociomatrix, etc.),...
Definition matrix.h:71
void operator*=(Matrix &b)
Multiplies (right) this m x n matrix with given n x p matrix b, replacing this matrix's own contents ...
Definition matrix.cpp:483
friend QTextStream & operator<<(QTextStream &os, Matrix &m)
Prints matrix m to given textstream.
Definition matrix.cpp:2487
Matrix & expBySquaring2(Matrix &Y, Matrix &X, int n, bool symmetry=false)
Recursive algorithm implementing "Exponentiation by squaring". Also known as Fast Modulo Multiplicati...
Definition matrix.cpp:635
qreal * m_data
Definition matrix.h:244
void sum(Matrix &a, Matrix &b)
Matrix addition: sets this matrix to a + b, cell by cell. Same result as operator+(),...
Definition matrix.cpp:388
bool printHTMLTable(QTextStream &os, const bool markDiag=false, const bool &plain=false, const bool &printInfinity=true)
Writes this matrix as an HTML table to os, one row of table cells per matrix row.
Definition matrix.cpp:2615
void NeighboursNearestFarthest(qreal &min, qreal &max, int &imin, int &jmin, int &imax, int &jmax)
Like findMinMaxValues(), but skips the diagonal (r==c) and also reports which pair of distinct vertic...
Definition matrix.cpp:158
void multiplyRow(int row, qreal value)
Multiplies every element of the given row by value, in place. Complexity: O(cols()).
Definition matrix.cpp:337
Matrix & operator*(Matrix &b)
Matrix multiplication, operator *. Allows P = A * B, where A is this (m x n) and B is b (n x p); retu...
Definition matrix.cpp:451
void fillMatrix(qreal value)
Fills every cell of this matrix with the given value. Complexity: O(rows()*cols()).
Definition matrix.cpp:266
int cols()
Definition matrix.h:96
Matrix & cocitationMatrix()
Returns the cocitation matrix of this matrix (C = A * A^T). Allows T = A.cocitationMatrix()....
Definition matrix.cpp:934
void resize(const int m, const int n)
Resizes this matrix to m x n, discarding any previous contents. All cells start zero-initialized.
Definition matrix.cpp:101
Matrix & laplacianMatrix()
Returns the Laplacian of this matrix: an N x N matrix L = D - A, where D is this matrix's degreeMatri...
Definition matrix.cpp:973
void lubksb(Matrix &a, const int &n, int indx[], qreal b[])
Solves the set of n linear equations A·X = b, where A nxn matrix decomposed as L·U (L lower triangula...
Definition matrix.cpp:1249
void identityMatrix(int dim)
Makes this square matrix the identity square matrix I.
Definition matrix.cpp:184
qreal * operator[](const int &r)
Definition matrix.h:92
int m_rows
Definition matrix.h:246
int m_cols
Definition matrix.h:247
Matrix & distancesMatrix(const int &metric, const QString varLocation, const bool &diagonal, const bool &considerWeights, std::function< bool()> cancelCheck=nullptr)
Computes a dissimilarities matrix T: T(i,k) is how different variable i and variable k are,...
Definition matrix.cpp:1427
void setItem(const int r, const int c, const qreal elem)
Definition matrix.h:88
bool ludcmp(Matrix &a, const int &n, int indx[], qreal &d, std::function< bool()> cancelCheck=nullptr)
Given matrix a, it replaces a by the LU decomposition of a rowwise permutation of itself....
Definition matrix.cpp:1101
bool illDefined()
Checks whether this matrix is "ill-defined": whether any cell holds RAND_MAX, the sentinel value used...
Definition matrix.cpp:2791
qreal distanceEuclidean(qreal x[], int n)
Helper function, computes the Euclideian length (also known as L2 distance) of a vector: if x = (x1 x...
Definition matrix.cpp:733
qreal distanceManhattan(qreal x[], qreal y[], int n)
Helper function, takes to vectors and returns their Manhattan distance (also known as l1 norm,...
Definition matrix.cpp:713
Matrix & productSym(Matrix &a, Matrix &b)
OBSOLETE - no caller found anywhere in the codebase. Was intended to take two (N x N) symmetric matri...
Definition matrix.cpp:567
int size()
Definition matrix.h:100
Matrix & pow(int n, bool symmetry=false)
Returns the n-th power of this matrix (X^n), via exponentiation by squaring (see expBySquaring2())....
Definition matrix.cpp:601
Matrix & pearsonCorrelationCoefficients(Matrix &AM, const QString &varLocation="Rows", const bool &diagonal=false, std::function< bool()> cancelCheck=nullptr)
Computes the Pearson product-moment correlation coefficient between every pair of variables (AM's row...
Definition matrix.cpp:2193
void product(Matrix &A, Matrix &B, bool symmetry=false)
Matrix Multiplication. Given two matrices A (mxn) and B (nxp), computes their product and stores it i...
Definition matrix.cpp:524
void rebuildRowPtr()
Definition matrix.h:236
Matrix & operator-(Matrix &b)
Matrix subtraction, operator -. Subtracts b (same dimensions) from this matrix and returns the result...
Definition matrix.cpp:433
void powerIteration(qreal x[], qreal &xsum, qreal &xmax, int &xmaxi, qreal &xmin, int &xmini, const qreal eps, const int &maxIter, std::function< bool()> cancelCheck=nullptr, qreal *lambdaMax=nullptr)
Implementation of the Power method which computes the leading eigenvector x of this matrix,...
Definition matrix.cpp:788
~Matrix()
Destructor: frees the data buffer and the row-pointer index.
Definition matrix.cpp:71
Matrix(int rowDim=0, int colDim=0)
Constructs a rowDim x colDim matrix, all cells zero-initialized. Defaults to 0x0 (an empty matrix) - ...
Definition matrix.cpp:41
bool solve(qreal b[])
Solves the linear system A*x = b, where A is this matrix, in place: b is overwritten with the solutio...
Definition matrix.cpp:1372
Matrix & similarityMatrix(Matrix &AM, const int &measure, const QString varLocation="Rows", const bool &diagonal=false, const bool &considerWeights=true, std::function< bool()> cancelCheck=nullptr)
Computes a pairwise similarity matrix SCM: SCM(i,k) is how alike variable i and variable k are,...
Definition matrix.cpp:1823
bool inverse(Matrix &a, std::function< bool()> cancelCheck=nullptr)
Computes and returns the inverse of matrix a, into this matrix. Allows b.inverse(a)....
Definition matrix.cpp:1304
Matrix & subtractFromI()
Replaces this matrix with I - this (the identity matrix minus this matrix), in place....
Definition matrix.cpp:279
qreal ** m_rowPtr
Definition matrix.h:245
Matrix & inverseByGaussJordanElimination(Matrix &a)
Inverts matrix A by Gauss-Jordan elimination with partial pivoting: starts this matrix as the identit...
Definition matrix.cpp:1000
Matrix & degreeMatrix()
Returns the degree matrix of this matrix: a diagonal matrix where S(i,i) is the sum of row i (i....
Definition matrix.cpp:951
void findMinMaxValues(qreal &min, qreal &max, bool &hasRealNumbers)
Scans every cell of this matrix (including the diagonal) and reports the smallest and largest values ...
Definition matrix.cpp:124
void clearItem(int r, int c)
Definition matrix.h:94
void operator+=(Matrix &b)
Adds matrix b to this matrix, in place, cell by cell. Allows A += B. Complexity: O(rows()*cols()).
Definition matrix.cpp:403
void clear()
Frees this matrix's data buffer and row-pointer index and resets it to 0x0. Called at the start of re...
Definition matrix.cpp:84
void swapRows(int rowA, int rowB)
Swaps row rowA with row rowB of this matrix, element by element. Used by inverseByGaussJordanEliminat...
Definition matrix.cpp:301
void zeroMatrix(const int m, const int n)
Makes this matrix the zero matrix of size mxn.
Definition matrix.cpp:204
qreal item(int r, int c)
Definition matrix.h:86
void deleteRowColumn(int i)
Deletes row erased and column erased from this (square) matrix, shifting every later row/column back ...
Definition matrix.cpp:229
Matrix & transpose()
Returns the transpose of this matrix (T(i,j) = this(j,i)). Allows T = A.transpose()....
Definition matrix.cpp:908
bool printMatrixConsole(bool debug=true)
Prints this matrix as plain text, one line per row, cells right-aligned to a fixed width....
Definition matrix.cpp:2757
int rows()
Definition matrix.h:98
Matrix & operator+(Matrix &b)
Matrix addition, operator +. Adds this matrix and b (same dimensions) and returns the sum S....
Definition matrix.cpp:417
Matrix & operator=(Matrix &a)
Matrix equality/assignment , operator = Allows copying a matrix onto another using b=a where b,...
Definition matrix.cpp:359
void multiplyScalar(const qreal &f)
Multiplies every cell of this matrix, in place, by scalar f. Allows P.multiplyScalar(f)....
Definition matrix.cpp:322
void productByVector(qreal in[], qreal out[], const bool &leftMultiply=false)
Calculates the matrix-by-vector product Ax of this matrix (or the left product xA,...
Definition matrix.cpp:679
static const int METRIC_EUCLIDEAN_DISTANCE
Definition matrix.h:43
static const int METRIC_HAMMING_DISTANCE
Definition matrix.h:41
static const int METRIC_NONE
Definition matrix.h:38
static const int METRIC_CHEBYSHEV_MAXIMUM
Definition matrix.h:46
static const QString infinity
Definition matrix.h:34
static const int METRIC_MANHATTAN_DISTANCE
Definition matrix.h:44
static const int METRIC_COSINE_SIMILARITY
Definition matrix.h:42
static const int METRIC_PEARSON_COEFFICIENT
Definition matrix.h:45
static const int METRIC_JACCARD_INDEX
Definition matrix.h:40
static const int METRIC_SIMPLE_MATCHING
Definition matrix.h:39