Basic Image AlgorithmS Library  2.8.0
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
SparseMatrix.hh
1 /*
2 This file is part of the BIAS library (Basic ImageAlgorithmS).
3 
4 Copyright (C) 2003-2009 (see file CONTACT for details)
5 Multimediale Systeme der Informationsverarbeitung
6 Institut fuer Informatik
7 Christian-Albrechts-Universitaet Kiel
8 
9 
10 BIAS is free software; you can redistribute it and/or modify
11 it under the terms of the GNU Lesser General Public License as published by
12 the Free Software Foundation; either version 2.1 of the License, or
13 (at your option) any later version.
14 
15 BIAS is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU Lesser General Public License for more details.
19 
20 You should have received a copy of the GNU Lesser General Public License
21 along with BIAS; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 */
24 
25 #ifndef __SparseMatrix_hh__
26 #define __SparseMatrix_hh__
27 
28 #include "bias_config.h"
29 
30 
31 #include "Base/Math/Matrix.hh"
32 #include "Base/Math/Vector.hh"
33 #include <map>
34 #include <list>
35 #include <iostream>
36 
37 // threshold for zero elements
38 #define SPARSE_MATRIX_EPSILON 1e-12
39 
40 namespace BIAS {
41 
42  /** @class SparseMatrix
43  @brief Implementation of sparse matrix operations.
44  @author beder, rework by esquivel
45  @date 01/2007, rework 11/2008,
46  @note This implementation of a sparse matrix uses a flexible structure
47  that may be extended by further elements, without the need to
48  reallocate the data manually. This structure is realized using
49  a list of pairs.
50  */
51 class BIASMathBase_EXPORT SparseMatrix {
52 
53  public:
54 
55  /** @brief Default constructor for zero sparse matrix */
56  SparseMatrix(): maxRow_(0), maxCol_(0), numRow_(0), numCol_(0) {}
57 
58  /** @brief Default constructor for zero sparse matrix */
59  SparseMatrix(unsigned int numRow, unsigned int numCol): maxRow_(0), maxCol_(0), numRow_(numRow), numCol_(numCol) {}
60 
61  /** @brief Constructor from BIAS matrix */
63 
64 
65  /** @brief Default destructor */
67 
68  SparseMatrix& operator=(const SparseMatrix& S);
69 
70  /** @brief Returns the maximum number of rows (max non-zero entry). */
71  unsigned int GetRows() const { return maxRow_+1; }
72 
73  /** @brief Returns the maximum number of columns (max non-zero entry). */
74  unsigned int GetCols() const { return maxCol_+1; }
75 
76  /** @brief Returns the total number of rows (matrix size). */
77  unsigned int GetRowsNum() const { return numRow_; }
78 
79  /** @brief Returns the total number of columns (matrix size). */
80  unsigned int GetColsNum() const { return numCol_; }
81 
82  /** @brief Returns value of an element.
83  @note Not very efficient since it has to be tested first if
84  the element has been set already!
85  @author esquivel 11/2008 */
86  double GetElement(unsigned int row, unsigned int col) const;
87 
88  /** @brief Sets a new element or changes the value of an existing element.
89  @note Existing elements are removed by setting value to 0!
90  @author esquivel 11/2008 */
91  void SetElement(unsigned int row, unsigned int col, double val);
92 
93  /** @brief Sets a submatrix beginning at (row,col) from a dense matrix.
94  @brief NO part of the specified submatrix must have been set before!
95  */
96  void SetSubMatrix(unsigned int row, unsigned int col,
97  BIAS::Matrix<double> const &A,
98  unsigned int startRowInA, unsigned int startColInA,
99  unsigned int row_count, unsigned int col_count);
100 
101  /** @brief Returns transposed matrix in result (as sparse matrix). */
102  void Transpose(SparseMatrix &result);
103 
104  /** @brief Multiplies this elementwise with 'multiplier'. */
105  void MultiplyIP(const double multiplier);
106 
107  /** @brief Multiplies with A and returns result M*A. */
108  void Multiply(SparseMatrix &A, SparseMatrix &result);
109 
110  /** @brief Multiplies with transpose of A and returns result M*A'. */
111  void MultiplyWithTransposeOf(SparseMatrix &A, SparseMatrix &result);
112 
113  /** @brief Multiplies with vector x and returns result A*x. */
114  void Multiply(BIAS::Vector<double> &x, BIAS::Vector<double> &result);
115 
116  /** @brief Inverts matrix and returns inverse (as dense matrix) and
117  solution of linear equation system A^(-1)*x = b in result.
118  @attention Valid only for square matrices! */
119  int InvertAndSolve(BIAS::Vector<double> &b, BIAS::Matrix<double> &inverse,
120  BIAS::Vector<double> &result);
121 
122  /** @brief Inverts matrix and returns inverse (as sparse matrix) and
123  solution of linear equation system A^(-1)*x = b in result.
124  @attention Valid only for square matrices! */
125  int InvertAndSolve(BIAS::Vector<double> &b, SparseMatrix &inverse,
126  BIAS::Vector<double> &result);
127 
128  /** @brief Returns solution of linear equation system A*x = b. */
129  int Solve(BIAS::Vector<double> &b, BIAS::Vector<double> &result);
130 
131  /// @brief computes pseudo inverse and returns result in inverse
132  int PseudoInverse(BIAS::Matrix<double>& inverse);
133 
134  /// @brief computes pseudo inverse and returns result in inverse
135  int PseudoInverse(BIAS::SparseMatrix& inverse);
136 
137  /// @brief clears old matrix and reinits with given size
138  void Reinit(unsigned rows, unsigned cols);
139 
140  /** @brief Returns inverse matrix as dense matrix.
141  @attention Valid only for square matrices! */
142  int Invert(BIAS::Matrix<double> &inverse);
143 
144  /** @brief Returns inverse matrix as sparse matrix.
145  @attention Valid only for square matrices! */
146  int Invert(SparseMatrix &inverse);
147 
148  /* @brief Appends matrix H at the bottom (MATLAB notation: A = [A; H]). */
149  void AppendMatrixBottom (SparseMatrix &H);
150 
151  /* @brief Appends matrix H at the right (MATLAB notation: A = [A, H]). */
152  void AppendMatrixRight (SparseMatrix &H);
153 
154  /** @brief Returns this matrix as dense BIAS matrix in M. */
155  void GetAsDense(BIAS::Matrix<double> &M) const;
156 
157  /** @brief Returns submatrix as dense BIAS matrix in M.
158  @todo Not efficient because of row->column mapping... */
159  void GetAsDense(unsigned int row, unsigned int col, unsigned int numRows,
160  unsigned int numCols, BIAS::Matrix<double> &M) const;
161 
162  /** @brief Prints the contents of this matrix. */
163  void Print(std::string const &name, std::ostream &stream=std::cout) const;
164 
165  /** @brief Returns maximum element at diagonal (at least zero).
166  @param row Returns diagonal index of maximum (at least 0).
167  @author koeser 04/2007 */
168  double GetMaxDiagonalElement(unsigned int &index) const;
169  inline double GetMaxDiagonalElement() const {
170  unsigned int index; return GetMaxDiagonalElement(index);
171  };
172 
173  /** @brief Returns maximum element at given row (at least zero).
174  @param col Returns column index of maximum (at least 0).
175  @author esquivel 11/2008 */
176  double GetMaxRowElement(unsigned int row, unsigned int &col) const;
177  inline double GetMaxRowElement(unsigned int row) const {
178  unsigned int col; return GetMaxRowElement(row, col);
179  };
180 
181  /** @brief Returns maximum element at given column (at least zero).
182  @param row Returns row index of maximum (at least 0).
183  @todo Not efficient because of row->column mapping...
184  @author esquivel 11/2008 */
185  double GetMaxColumnElement(unsigned int col, unsigned int &row) const;
186  inline double GetMaxColumnElement(unsigned int col) const {
187  unsigned int row; return GetMaxColumnElement(col, row);
188  };
189 
190  /** @brief Runs across diagonal and adds value to diagonal elements.
191  @note If diagonal elements does not exist, it is created.
192  @attention Implemented only for square matrices!
193  @author koeser 04/2007 */
194  void AddToDiagonal(const double &value);
195 
196  /** @brief Runs across diagonal and multiplies diagonal element with value.
197  @author koeser 04/2007 */
198  void MultiplyDiagonalBy(const double &value);
199 
200  /** @brief Checks if this sparse matrix is still consistent, i.e.
201  order of rows and columns is strictly ascending, and there
202  are no empty rows, no values below epsilon and no values
203  outside of the matrix boundaries given by maxRow_, maxCol_!
204  @return Returns true if matrix is consistent, false otherwise.
205  @author esquivel 11/2008 */
206  bool CheckConsistency();
207 
208  /** @brief Return rows, columns and values for all elements in matrix.
209  @param rows Returns row indices of elements.
210  @param cols Returns column indices of elements.
211  @param values Returns values of elements.
212  */
213  void GetAllElements(std::vector<unsigned int> &rows,
214  std::vector<unsigned int> &cols,
215  std::vector<double> &values) const;
216 
217  protected:
218 
219  /** @brief Insert an element.
220  @note The element must NOT have been set before!
221  */
222  void InsertElement_(unsigned int row, unsigned int col, double value);
223 
224  /** @brief Performs Gauss-Jordan algorithm on sparse matrix. */
225  int GaussJordan_();
226 
227  /** @brief Maps row indices to mappings from column indices to values. */
228  std::map<unsigned int, std::list<std::pair<unsigned int, double> > > rows_;
229 
230  /** @brief Current max. row and column containing non-zero elements. */
231  unsigned int maxRow_, maxCol_;
232 
233  /** @brief Indicates the current number of rows and clumns.
234  values are negative, if the dimensions of the matrix are unknown.*/
235  unsigned int numRow_, numCol_;
236 
237  };
238 
239  inline std::ostream& operator<<(std::ostream& stream,
240  const BIAS::SparseMatrix& matrix)
241  {
242  matrix.Print("SparseMatrix", stream);
243  return stream;
244  }
245 
246 }
247 
248 #endif
double GetMaxRowElement(unsigned int row) const
void Print(std::string const &name, std::ostream &stream=std::cout) const
Prints the contents of this matrix.
unsigned int maxRow_
Current max.
std::map< unsigned int, std::list< std::pair< unsigned int, double > > > rows_
Maps row indices to mappings from column indices to values.
double GetMaxDiagonalElement() const
SparseMatrix(unsigned int numRow, unsigned int numCol)
Default constructor for zero sparse matrix.
Definition: SparseMatrix.hh:59
~SparseMatrix()
Default destructor.
Definition: SparseMatrix.hh:66
unsigned int GetRows() const
Returns the maximum number of rows (max non-zero entry).
Definition: SparseMatrix.hh:71
Implementation of sparse matrix operations.
Definition: SparseMatrix.hh:51
unsigned int numRow_
Indicates the current number of rows and clumns.
unsigned int GetCols() const
Returns the maximum number of columns (max non-zero entry).
Definition: SparseMatrix.hh:74
std::ostream & operator<<(std::ostream &os, const Array2D< T > &arg)
Definition: Array2D.hh:260
SparseMatrix()
Default constructor for zero sparse matrix.
Definition: SparseMatrix.hh:56
unsigned int GetRowsNum() const
Returns the total number of rows (matrix size).
Definition: SparseMatrix.hh:77
double GetMaxColumnElement(unsigned int col) const
unsigned int GetColsNum() const
Returns the total number of columns (matrix size).
Definition: SparseMatrix.hh:80