Code Documentation 3.8
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 bool hasNegativeEntry();
105
106 void NeighboursNearestFarthest(qreal&min,qreal&max,
107 int &imin, int &jmin,
108 int &imax, int &jmax);
109
110 void deleteRowColumn(int i); /* deletes row i and column i */
111
112 void identityMatrix (int dim);
113
114 void zeroMatrix (const int m, const int n);
115
116 void fillMatrix (qreal value );
117
119
120
121 Matrix& operator =(const Matrix & a);
122
123 void sum(Matrix &a, Matrix &b) ;
124
125 void operator +=(Matrix & b);
126
128
130
132 void operator *=(Matrix & b);
133
134 void product( Matrix &A, Matrix & B, bool symmetry=false) ;
135
136 Matrix & productSym( Matrix &a, Matrix & b) ;
137
138 void swapRows(int rowA,int rowB);
139
140 void multiplyScalar(const qreal &f);
141 void multiplyRow(int row, qreal value);
142
143 void productByVector (
144 qreal in[],
145 qreal out[],
146 const bool &leftMultiply=false);
147
148 Matrix pow (int n, bool symmetry=false) ;
149 Matrix expBySquaring2 (Matrix &Y, Matrix &X, int n, bool symmetry=false);
150
151 qreal distanceManhattan(
152 qreal x[],
153 qreal y[],
154 int n);
155 qreal distanceEuclidean(
156 qreal x[],
157 int n);
158
159 void powerIteration (
160 qreal x[] ,
161 qreal &xsum,
162 qreal &xmax,
163 int &xmaxi,
164 qreal &xmin,
165 int &xmini,
166 const qreal eps, const int &maxIter,
167 std::function<bool()> cancelCheck = nullptr,
168 qreal *lambdaMax = nullptr);
169
170 qreal spectralRadiusExact(const qreal eps = 0.0000001, const int maxIter = 500,
171 std::function<bool()> cancelCheck = nullptr);
172
173 qreal spectralRadiusBound();
174
176
178
179 Matrix& transpose();
180
182
183
185
186 bool inverse(Matrix &a, std::function<bool()> cancelCheck = nullptr);
187
188 bool solve(qreal b[]);
189
190 bool ludcmp (Matrix &a, const int &n, int indx[], qreal &d, std::function<bool()> cancelCheck = nullptr) ;
191
192 void lubksb (Matrix &a, const int &n, int indx[], qreal b[]);
193
194
195 Matrix& distancesMatrix(const int &metric,
196 const QString varLocation,
197 const bool &diagonal,
198 const bool &considerWeights,
199 std::function<bool()> cancelCheck = nullptr);
200
202 const int &measure,
203 const QString varLocation="Rows",
204 const bool &diagonal=false,
205 const bool &considerWeights=true,
206 std::function<bool()> cancelCheck = nullptr);
207
208
210 const QString &varLocation="Rows",
211 const bool &diagonal=false,
212 std::function<bool()> cancelCheck = nullptr);
213
214
215 friend QTextStream& operator << (QTextStream& os, Matrix& m);
216 bool printHTMLTable(QTextStream& os,
217 const bool markDiag=false,
218 const bool &plain=false,
219 const bool &printInfinity=true);
220 bool printMatrixConsole(bool debug=true);
221
222 bool illDefined();
223
224private:
225 // Builds m_rowPtr[]: a lookup table of row-start pointers into m_data, one entry per
226 // row, so item()/setItem()/operator[] never have to recompute a row's address from
227 // scratch. Concretely: m_rowPtr is an array of m_rows pointers; entry r is set to
228 // "m_data, advanced by r whole rows" (r*m_cols cells). Looking up cell (r,c) then
229 // becomes "read m_rowPtr[r] to get row r's address, then step c cells forward from
230 // it" - one array read plus one cheap offset, regardless of how large the matrix is,
231 // versus recomputing r*m_cols (a real multiplication) on every single access.
232 //
233 // Must be called once after every place that gives m_data a new address or a new
234 // m_cols - the constructor, the copy constructor, resize(), identityMatrix(),
235 // zeroMatrix(), deleteRowColumn(), and the branch of operator=() that reallocates -
236 // because every entry in the old m_rowPtr[] would otherwise point at stale memory or
237 // use the wrong row width. Complexity: O(m_rows) - one pointer computed per row, not
238 // per cell, which is what keeps this cheap even for large matrices.
239 //
240 // This function only allocates and fills; it does not free a previous m_rowPtr array.
241 // Callers that already have one from an earlier allocation must free it themselves
242 // first (via clear(), or a direct delete[] - see deleteRowColumn()) before calling this.
244 m_rowPtr = new (nothrow) qreal*[m_rows];
245 Q_CHECK_PTR( m_rowPtr );
246 for (int i=0; i<m_rows; i++) {
247 m_rowPtr[i] = m_data + static_cast<size_t>(i) * m_cols;
248 }
249 }
250
251 qreal *m_data; // the actual N*M cells, one allocation, row-major.
252 qreal **m_rowPtr; // m_rowPtr[r] == m_data + r*m_cols, precomputed for every row.
255
256};
257
258
259
260
261
262#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:511
friend QTextStream & operator<<(QTextStream &os, Matrix &m)
Prints matrix m to given textstream.
Definition matrix.cpp:2725
qreal * m_data
Definition matrix.h:251
void sum(Matrix &a, Matrix &b)
Matrix addition: sets this matrix to a + b, cell by cell. Same result as operator+(),...
Definition matrix.cpp:416
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:2853
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:186
void multiplyRow(int row, qreal value)
Multiplies every element of the given row by value, in place. Complexity: O(cols()).
Definition matrix.cpp:365
void fillMatrix(qreal value)
Fills every cell of this matrix with the given value. Complexity: O(rows()*cols()).
Definition matrix.cpp:294
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:1117
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:1156
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:1433
void identityMatrix(int dim)
Makes this square matrix the identity square matrix I.
Definition matrix.cpp:212
qreal * operator[](const int &r)
Definition matrix.h:92
int m_rows
Definition matrix.h:253
int m_cols
Definition matrix.h:254
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:1615
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:1284
bool illDefined()
Checks whether this matrix is "ill-defined": whether any cell holds RAND_MAX, the sentinel value used...
Definition matrix.cpp:3029
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:778
bool hasNegativeEntry()
Scans every cell of this matrix (including the diagonal) and reports the smallest and largest values ...
Definition matrix.cpp:137
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:479
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:758
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:605
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:639
int size()
Definition matrix.h:100
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:2402
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:552
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:673
void rebuildRowPtr()
Definition matrix.h:243
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:849
~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
qreal spectralRadiusBound()
Returns a safe upper bound on this matrix's spectral radius (max |eigenvalue|), via Gerschgorin's cir...
Definition matrix.cpp:1059
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:1556
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:2012
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:1488
Matrix & subtractFromI()
Replaces this matrix with I - this (the identity matrix minus this matrix), in place....
Definition matrix.cpp:307
qreal ** m_rowPtr
Definition matrix.h:252
Matrix & inverseByGaussJordanElimination(Matrix &a)
Inverts matrix A by Gauss-Jordan elimination with partial pivoting: starts this matrix as the identit...
Definition matrix.cpp:1183
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:1134
Matrix operator-(Matrix &b)
Matrix subtraction, operator -. Subtracts b (same dimensions) from this matrix and returns the result...
Definition matrix.cpp:461
void findMinMaxValues(qreal &min, qreal &max, bool &hasRealNumbers)
Definition matrix.cpp:152
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:431
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:329
void zeroMatrix(const int m, const int n)
Makes this matrix the zero matrix of size mxn.
Definition matrix.cpp:232
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:257
Matrix & transpose()
Returns the transpose of this matrix (T(i,j) = this(j,i)). Allows T = A.transpose()....
Definition matrix.cpp:1091
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:2995
int rows()
Definition matrix.h:98
Matrix & operator=(const Matrix &a)
Matrix equality/assignment , operator = Allows copying a matrix onto another using b=a where b,...
Definition matrix.cpp:387
Matrix operator+(Matrix &b)
Matrix addition, operator +. Adds this matrix and b (same dimensions) and returns the sum S....
Definition matrix.cpp:445
qreal spectralRadiusExact(const qreal eps=0.0000001, const int maxIter=500, std::function< bool()> cancelCheck=nullptr)
Estimates this matrix's spectral radius (dominant eigenvalue magnitude) exactly, via power iteration ...
Definition matrix.cpp:980
void multiplyScalar(const qreal &f)
Multiplies every cell of this matrix, in place, by scalar f. Allows P.multiplyScalar(f)....
Definition matrix.cpp:350
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:717
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