Main MRPT website > C++ reference
MRPT logo
CSparseMatrixTemplate.h
Go to the documentation of this file.
1 /* +---------------------------------------------------------------------------+
2  | The Mobile Robot Programming Toolkit (MRPT) |
3  | |
4  | http://www.mrpt.org/ |
5  | |
6  | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file |
7  | Copyright (c) 2005-2013, MAPIR group, University of Malaga |
8  | Copyright (c) 2012-2013, University of Almeria |
9  | All rights reserved. |
10  | |
11  | Redistribution and use in source and binary forms, with or without |
12  | modification, are permitted provided that the following conditions are |
13  | met: |
14  | * Redistributions of source code must retain the above copyright |
15  | notice, this list of conditions and the following disclaimer. |
16  | * Redistributions in binary form must reproduce the above copyright |
17  | notice, this list of conditions and the following disclaimer in the |
18  | documentation and/or other materials provided with the distribution. |
19  | * Neither the name of the copyright holders nor the |
20  | names of its contributors may be used to endorse or promote products |
21  | derived from this software without specific prior written permission.|
22  | |
23  | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
24  | 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED |
25  | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR|
26  | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE |
27  | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL|
28  | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR|
29  | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) |
30  | HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |
31  | STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN |
32  | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
33  | POSSIBILITY OF SUCH DAMAGE. |
34  +---------------------------------------------------------------------------+ */
35 #ifndef CSparseMatrixTemplate_H
36 #define CSparseMatrixTemplate_H
37 
38 #include <mrpt/utils/utils_defs.h>
39 
40 namespace mrpt {
41 namespace math {
42  using namespace std;
43 
44  /** A sparse matrix container (with cells of any type), with iterators.
45  * This class stores only those elements created by assigning them a value, for example: "M(2,3)=8;".
46  *
47  * This class doesn't implement math operations since it's a generic sparse container, but it can be
48  * used to initialize the contents of a CSparse library-based matrix of type mrpt::math::CSparseMatrix.
49  *
50  * Note that reading non-existing cell elements will return the default value (0 for numbers)
51  * and that cell will remain non-created in the matrix.
52  *
53  * There is an additional method "exists(i,j)" to check whether a given element exists in the matrix.
54  *
55  * \sa mrpt::math::MatrixBlockSparseCols, mrpt::math::CSparseMatrix, CSparseSymmetricalMatrix
56  * \note Methods marked as "Doesn't check bounds" mean that if an access to an element out of the matrix size is tried, an empty element will be assumed, but this will not raise any invalid memory access.
57  * \ingroup mrpt_base_grp
58  */
59  template<class T>
61  //Public typedefs
62  public:
63  /**
64  * Internal map type, used to store the actual matrix.
65  */
66  typedef typename std::map<std::pair<size_t,size_t>,T> SparseMatrixMap;
67  /**
68  * Const iterator to move through the matrix.
69  * \sa CSparseMatrixTemplate::const_reverse_iterator
70  */
72  /**
73  * Const reverse iterator to move through the matrix.
74  * \sa CSparseMatrixTemplate::const_iterator
75  */
76  typedef typename SparseMatrixMap::const_reverse_iterator const_reverse_iterator;
77  protected:
78  /**
79  * Size of the matrix.
80  */
81  size_t mRows,mColumns;
82  /**
83  * Actual matrix.
84  */
86  public:
87  /**
88  * Basic constructor with no data. Size is set to (0,0).
89  */
90  CSparseMatrixTemplate():mRows(0),mColumns(0) {}
91  /**
92  * Constructor with default size.
93  */
94  CSparseMatrixTemplate(size_t nR,size_t nC):mRows(nR),mColumns(nC) {}
95  /**
96  * Element access operator. Doesn't check bounds.
97  */
98  inline T operator()(size_t r,size_t c) const {
99  const_iterator it=objectList.find(make_pair(r,c));
100  if (it==objectList.end()) return T();
101  else return it->second;
102  }
103 
104  /** Element access operator. Checks bounds.
105  */
106  inline bool exists(size_t r,size_t c) const {
107 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
108  if (r>=mRows||c>=mColumns) throw std::logic_error("Out of range");
109 #endif
110  return (objectList.find(make_pair(r,c)) != objectList.end());
111  }
112 
113  /**
114  * Reference access operator. Checks for bounds.
115  */
116  inline T& operator()(size_t r,size_t c) {
117 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
118  if (r>=mRows||c>=mColumns) throw std::logic_error("Out of range");
119 #endif
120  return objectList[make_pair(r,c)];
121  }
122  /**
123  * Returns the amount of rows in this matrix.
124  * \sa getColCount,getRow
125  */
126  inline size_t getRowCount() const {
127  return mRows;
128  }
129  /**
130  * Returns the amount of columns in this matrix.
131  * \sa getRowCount
132  */
133  inline size_t getColCount() const {
134  return mColumns;
135  }
136  /**
137  * Extracts a full row from the matrix.
138  * \sa getRowCount,getColumn,setRow
139  * \throw std::logic_error on out of range.
140  */
141  void getRow(size_t nRow,std::vector<T> &vec) const {
142 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
143  if (nRow>=mRows) throw std::logic_error("Out of range");
144 #endif
145  vec.resize(mColumns);
146  size_t nextIndex=0;
147  for (typename SparseMatrixMap::const_iterator it=objectList.begin();it!=objectList.end();++it) {
148  const pair<size_t,size_t> &index=it->first;
149  if (index.first<nRow) continue;
150  else if (index.first==nRow) {
151  for (size_t i=nextIndex;i<index.second;i++) vec[i]=T();
152  vec[index.second]=it->second;
153  nextIndex=index.second+1;
154  } else {
155  for (size_t i=nextIndex;i<mColumns;i++) vec[i]=T();
156  break;
157  }
158  }
159  }
160  /**
161  * Extracts a full column from the matrix.
162  * \sa getColCount,getRow,setColumn
163  * \throw std::logic_error on out of range.
164  */
165  void getColumn(size_t nCol,std::vector<T> &vec) const {
166 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
167  if (nCol>=mColumns) throw std::logic_error("Out of range");
168 #endif
169  vec.resize(mRows);
170  size_t nextIndex=0;
171  for (typename SparseMatrixMap::const_iterator it=objectList.begin();it!=objectList.end();++it) {
172  const pair<size_t,size_t> &index=it->first;
173  if (index.second==nCol) {
174  for (size_t i=nextIndex;i<index.first;i++) vec[i]=T();
175  vec[index.first]=it->second;
176  nextIndex=index.first+1;
177  }
178  }
179  for (size_t i=nextIndex;i<mRows;i++) vec[i]=T();
180  }
181  /**
182  * Inserts an element into the matrix.
183  * \sa operator()(size_t,size_t)
184  */
185  inline void insert(size_t row,size_t column,const T& obj) {
186  operator()(row,column)=obj;
187  }
188 
189  /** Inserts submatrix at a given location */
190  template <class MATRIX_LIKE>
191  inline void insertMatrix(size_t row,size_t column,const MATRIX_LIKE& mat)
192  {
193  for (size_t nr=0;nr<mat.getRowCount();nr++)
194  for (size_t nc=0;nc<mat.getColCount();nc++)
195  operator()(row+nr,column+nc)=mat(nr,nc);
196  }
197 
198  //Public interface only supports const iterators. This way, no user of this class will be able to freely modify it contents.
199  /**
200  * Returns an iterator which points to the starting point of the matrix. It's a const_iterator, so that the usar isn't able to modify the matrix content into an invalid state.
201  * \sa end,rbegin,rend
202  */
203  inline const_iterator begin() const {
204  return objectList.begin();
205  }
206  /**
207  * Returns an iterator which points to the end of the matrix. It's a const_iterator, so that the usar isn't able to modify the matrix content into an invalid state.
208  * \sa begin,rbegin,rend
209  */
210  inline const_iterator end() const {
211  return objectList.end();
212  }
213  /**
214  * Returns an iterator which points to the end of the matrix, and can be used to move backwards. It's a const_reverse_iterator, so that the usar isn't able to modify the matrix content into an invalid state.
215  * \sa begin,end,rend
216  */
218  return objectList.rbegin();
219  }
220  /**
221  * Returns an iterator which points to the starting point of the matrix, although it's the upper limit of the matrix since it's a reverse iterator. Also, it's a const_reverse_iterator, so that the usar isn't able to modify the matrix content into an invalid state.
222  * \sa begin,end,rbegin
223  */
224  inline const_reverse_iterator rend() const {
225  return objectList.rend();
226  }
227  /**
228  * Inserts a full row into the matrix. The third argument is used to specify a null object (which won't be inserted, since the matrix is sparse).
229  * \sa getRow
230  * \throw std::logic_error on out of range or wrong sized vector.
231  */
232  void setRow(size_t nRow,const std::vector<T> &vec,const T& nullObject=T()) {
233 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
234  if (nRow>=mRows) throw std::logic_error("Out of range");
235 #endif
236  size_t N=vec.size();
237  if (N!=mColumns) throw std::logic_error("Wrong-sized vector");
238  for (size_t i=0;i<N;i++) {
239  const T &obj=vec[i];
240  pair<size_t,size_t> index=make_pair(nRow,i);
241  if (obj==nullObject) objectList.erase(index);
242  else objectList[index]=obj;
243  }
244  }
245  /**
246  * Inserts a full column into the matrix. The third argument is used to specify a null object (which won't be inserted, since the matrix is sparse).
247  * \sa getColumn
248  * \throw std::logic_error on out of range or wrong sized vector.
249  */
250  void setColumn(size_t nCol,const std::vector<T> &vec,const T& nullObject=T()) {
251 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
252  if (nCol>=mColumns) throw std::logic_error("Out of range");
253 #endif
254  size_t N=vec.size();
255  if (N!=mRows) throw std::logic_error("Wrong-sized vector");
256  for (size_t i=0;i<N;i++) {
257  const T &obj=vec[i];
258  pair<size_t,size_t> index=make_pair(i,nCol);
259  if (obj==nullObject) objectList.erase(index);
260  else objectList[index]=obj;
261  }
262  }
263  /**
264  * Changes the size of the matrix.
265  */
266  void resize(size_t nRows,size_t nCols) {
267  // if (mRows<0||mColumns<0) throw std::logic_error("Invalid range"); // This case never happens!
268  if (mRows==nRows && mColumns==nCols) return;
269  mRows=nRows;
270  mColumns=nCols;
271  std::vector<pair<size_t,size_t> > toErase;
272  for (const_iterator it=objectList.begin();it!=objectList.end();++it) {
273  const pair<size_t,size_t> &i=it->first;
274  if (i.first>=nRows||i.second>=nCols) toErase.push_back(it->first);
275  }
276  for (std::vector<pair<size_t,size_t> >::const_iterator it=toErase.begin();it!=toErase.end();++it) objectList.erase(*it);
277  }
278  /**
279  * Extracts a submatrix form the matrix.
280  * \sa operator()(size_t,size_t)
281  * \throw std::logic_error on invalid bounds.
282  */
283  CSparseMatrixTemplate<T> operator()(size_t firstRow,size_t lastRow,size_t firstColumn,size_t lastColumn) const {
284 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
285  if (lastRow>=mRows||lastColumn>=mColumns) throw std::logic_error("Out of range");
286  if (firstRow>lastRow||firstColumn>lastColumn) throw std::logic_error("Invalid size");
287 #endif
288  CSparseMatrixTemplate<T> res=CSparseMatrixTemplate<T>(lastRow+1-firstRow,lastColumn+1-firstColumn);
289  for (typename SparseMatrixMap::const_iterator it=begin();it!=end();++it) {
290  const pair<size_t,size_t> &i=it->first;
291  if (i.first>=firstRow&&i.first<=lastRow&&i.second>=firstColumn&&i.second<=lastColumn) res(i.first-firstRow,i.second-firstColumn)=it->second;
292  }
293  return res;
294  }
295  /**
296  * Gets a vector containing all the elements of the matrix, ignoring their position.
297  */
298  void getAsVector(std::vector<T> &vec) const {
299  size_t N=objectList.size();
300  vec.resize(0);
301  vec.reserve(N);
302  for (const_iterator it=objectList.begin();it!=objectList.end();++it) vec.push_back(it->second);
303  }
304  /**
305  * Gets the amount of non-null elements inside the matrix.
306  * \sa getNullElements,isNull,isNotNull
307  */
308  inline size_t getNonNullElements() const {
309  return objectList.size();
310  }
311  /** Are there no elements set to !=0 ?
312  * \sa getNullElements,isNull,isNotNull
313  */
314  inline bool empty() const { return objectList.empty(); }
315 
316  /**
317  * Gets the amount of null elements inside the matrix.
318  * \sa getNonNullElements,isNull,isNotNull
319  */
320  inline size_t getNullElements() const {
321  return mRows*mColumns-getNonNullElements();
322  }
323  /**
324  * Checks whether an element of the matrix is the default object.
325  * \sa getNonNullElements,getNullElements,isNotNull
326  * \throw std::logic_error on out of range
327  */
328  inline bool isNull(size_t nRow,size_t nCol) const {
329  if (nRow>=mRows||nCol>=mColumns) throw std::logic_error("Out of range");
330  return objectList.count(make_pair(nRow,nCol))==0;
331  }
332  /**
333  * Checks whether an element of the matrix is not the default object.
334  * \sa getNonNullElements,getNullElements,isNull
335  */
336  inline bool isNotNull(size_t nRow,size_t nCol) const {
337  if (nRow>=mRows||nCol>=mColumns) throw std::logic_error("Out of range");
338  return objectList.count(make_pair(nRow,nCol))>0;
339  }
340  /**
341  * Completely removes all elements, although maintaining the matrix's size.
342  */
343  inline void clear() {
344  objectList.clear();
345  }
346  /**
347  * Checks each non-null elements against the basic objects, erasing unnecesary references to it.
348  */
349  void purge(T nullObject=T()) {
350  std::vector<std::pair<size_t,size_t> > nulls;
351  for (const_iterator it=begin();it!=end();++it) if (it->second==nullObject) nulls.push_back(it->first);
352  for (std::vector<std::pair<size_t,size_t> >::const_iterator it=nulls.begin();it!=nulls.end();++it) objectList.erase(*it);
353  }
354  }; // end of sparse matrix
355 
356  /** A sparse matrix container for square symmetrical content around the main diagonal.
357  * This class saves half of the space with respect to CSparseMatrixTemplate since only those entries (c,r) such as c>=r are really stored,
358  * but both (c,r) and (r,c) can be retrieved or set and both redirect to the same internal cell container.
359  * \sa CSparseMatrixTemplate
360  */
361  template<class T>
363  public:
368 
369  void resize(size_t matrixSize) {
370  CSparseMatrixTemplate<T>::resize(matrixSize,matrixSize);
371  }
372 
373  inline T operator()(size_t r,size_t c) const {
374  if (c<r) std::swap(r,c); // Symmetrical matrix
376  if (it==CSparseMatrixTemplate<T>::objectList.end()) return T();
377  else return it->second;
378  }
379  inline T& operator()(size_t r,size_t c) {
380  if (c<r) std::swap(r,c); // Symmetrical matrix
381  if (r>=CSparseMatrixTemplate<T>::mRows||c>=CSparseMatrixTemplate<T>::mColumns) throw std::logic_error("Out of range");
382  return CSparseMatrixTemplate<T>::objectList[make_pair(r,c)];
383  }
384 
385  }; // end of CSparseSymmetricalMatrix
386 
387 }
388 }
389 #endif
void insertMatrix(size_t row, size_t column, const MATRIX_LIKE &mat)
Inserts submatrix at a given location.
const_iterator begin() const
Returns an iterator which points to the starting point of the matrix.
bool isNotNull(size_t nRow, size_t nCol) const
Checks whether an element of the matrix is not the default object.
size_t getNullElements() const
Gets the amount of null elements inside the matrix.
EIGEN_STRONG_INLINE iterator end()
Definition: eigen_plugins.h:53
size_t getNonNullElements() const
Gets the amount of non-null elements inside the matrix.
EIGEN_STRONG_INLINE iterator begin()
Definition: eigen_plugins.h:52
size_t getColCount() const
Returns the amount of columns in this matrix.
void setColumn(size_t nCol, const std::vector< T > &vec, const T &nullObject=T())
Inserts a full column into the matrix.
STL namespace.
void insert(size_t row, size_t column, const T &obj)
Inserts an element into the matrix.
const Scalar * const_iterator
Definition: eigen_plugins.h:50
SparseMatrixMap::const_iterator const_iterator
Const iterator to move through the matrix.
T & operator()(size_t r, size_t c)
Reference access operator.
CSparseSymmetricalMatrix(const CSparseSymmetricalMatrix &o)
A sparse matrix container (with cells of any type), with iterators.
bool empty() const
Are there no elements set to !=0 ?
void purge(T nullObject=T())
Checks each non-null elements against the basic objects, erasing unnecesary references to it...
size_t getRowCount() const
Returns the amount of rows in this matrix.
CSparseMatrixTemplate(size_t nR, size_t nC)
Constructor with default size.
T operator()(size_t r, size_t c) const
Element access operator.
SparseMatrixMap::const_reverse_iterator const_reverse_iterator
Const reverse iterator to move through the matrix.
void getColumn(size_t nCol, std::vector< T > &vec) const
Extracts a full column from the matrix.
CSparseMatrixTemplate()
Basic constructor with no data.
size_t mRows
Size of the matrix.
const_reverse_iterator rend() const
Returns an iterator which points to the starting point of the matrix, although it&#39;s the upper limit o...
void clear()
Completely removes all elements, although maintaining the matrix&#39;s size.
CSparseSymmetricalMatrix(const CSparseMatrixTemplate< T > &o)
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
const_iterator end() const
Returns an iterator which points to the end of the matrix.
bool isNull(size_t nRow, size_t nCol) const
Checks whether an element of the matrix is the default object.
T operator()(size_t r, size_t c) const
CSparseMatrixTemplate< T > operator()(size_t firstRow, size_t lastRow, size_t firstColumn, size_t lastColumn) const
Extracts a submatrix form the matrix.
SparseMatrixMap objectList
Actual matrix.
void resize(size_t nRows, size_t nCols)
Changes the size of the matrix.
bool exists(size_t r, size_t c) const
Element access operator.
std::map< std::pair< size_t, size_t >, T > SparseMatrixMap
Internal map type, used to store the actual matrix.
const_reverse_iterator rbegin() const
Returns an iterator which points to the end of the matrix, and can be used to move backwards...
void getAsVector(std::vector< T > &vec) const
Gets a vector containing all the elements of the matrix, ignoring their position. ...
void getRow(size_t nRow, std::vector< T > &vec) const
Extracts a full row from the matrix.
void setRow(size_t nRow, const std::vector< T > &vec, const T &nullObject=T())
Inserts a full row into the matrix.
A sparse matrix container for square symmetrical content around the main diagonal.



Page generated by Doxygen 1.8.14 for MRPT 1.0.2 SVN: at lun oct 28 00:52:41 CET 2019 Hosted on:
SourceForge.net Logo