rheolef  6.3
ublas-invert.h
Go to the documentation of this file.
1 #ifndef _RHEOLEF_UBLAS_INVERT_H
2 #define _RHEOLEF_UBLAS_INVERT_H
3 // http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?action=browse&diff=1&id=LU_Matrix_Inversion
4 #include <boost/numeric/ublas/vector.hpp>
5 #include <boost/numeric/ublas/vector_proxy.hpp>
6 #include <boost/numeric/ublas/matrix.hpp>
7 #include <boost/numeric/ublas/triangular.hpp>
8 #include <boost/numeric/ublas/lu.hpp>
9 #include <boost/numeric/ublas/io.hpp>
10 namespace ublas = boost::numeric::ublas;
11 
12 namespace rheolef {
13 template<class T>
14 bool invert (const ublas::matrix<T>& input, ublas::matrix<T>& inverse) {
15  using namespace boost::numeric::ublas;
16  typedef permutation_matrix<std::size_t> pmatrix;
17  matrix<T> A(input);
18  pmatrix pm(A.size1());
19 
20  int res = lu_factorize(A,pm);
21  if( res != 0 ) return false;
22 
23  inverse.assign(ublas::identity_matrix<T>(A.size1()));
24 
25  lu_substitute(A, pm, inverse);
26 
27  return true;
28 }
29 template<class T>
30 boost::numeric::ublas::matrix<T>
31 invert(const boost::numeric::ublas::matrix<T> &m, bool &is_singular)
32 {
33  ublas::matrix<T> inv_m (m.size1(), m.size2());
34  is_singular = ! invert (m, inv_m);
35  return inv_m;
36 }
37 // http://archives.free.net.ph/message/20080909.064313.59c122c4.fr.html
38 template<class matrix_T>
39 double determinant(ublas::matrix_expression<matrix_T> const& mat_r) {
40  double det = 1.0;
41  matrix_T mLu(mat_r());
42  ublas::permutation_matrix<std::size_t> pivots(mat_r().size1() );
43  bool is_singular = lu_factorize(mLu, pivots);
44  if (!is_singular) {
45  for (std::size_t i = 0; i < pivots.size(); ++i) {
46  if (pivots(i) != i) {
47  det *= -1.0;
48  }
49  det *= mLu(i,i);
50  }
51  } else {
52  det = 0.0;
53  }
54  return det;
55 }
56 }// namespace rheolef
57 #endif // _RHEOLEF_UBLAS_INVERT_H
58