gram_schmidt.hpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. boost header: numeric/odeint/gram_schmitt.hpp
  3. Copyright 2011-2013 Karsten Ahnert
  4. Copyright 2011 Mario Mulansky
  5. Distributed under the Boost Software License, Version 1.0.
  6. (See accompanying file LICENSE_1_0.txt or
  7. copy at http://www.boost.org/LICENSE_1_0.txt)
  8. */
  9. #ifndef BOOST_NUMERIC_ODEINT_GRAM_SCHMITT_HPP_INCLUDED
  10. #define BOOST_NUMERIC_ODEINT_GRAM_SCHMITT_HPP_INCLUDED
  11. #include <boost/throw_exception.hpp>
  12. #include <iterator>
  13. #include <algorithm>
  14. #include <numeric>
  15. namespace boost {
  16. namespace numeric {
  17. namespace odeint {
  18. template< class Iterator , class T >
  19. void normalize( Iterator first , Iterator last , T norm )
  20. {
  21. while( first != last ) *first++ /= norm;
  22. }
  23. template< class Iterator , class T >
  24. void substract_vector( Iterator first1 , Iterator last1 ,
  25. Iterator first2 , T val )
  26. {
  27. while( first1 != last1 ) *first1++ -= val * ( *first2++ );
  28. }
  29. template< size_t num_of_lyap , class StateType , class LyapType >
  30. void gram_schmidt( StateType &x , LyapType &lyap , size_t n )
  31. {
  32. if( !num_of_lyap ) return;
  33. if( ptrdiff_t( ( num_of_lyap + 1 ) * n ) != std::distance( x.begin() , x.end() ) )
  34. BOOST_THROW_EXCEPTION( std::domain_error( "renormalization() : size of state does not match the number of lyapunov exponents." ) );
  35. typedef typename StateType::value_type value_type;
  36. typedef typename StateType::iterator iterator;
  37. value_type norm[num_of_lyap];
  38. value_type tmp[num_of_lyap];
  39. iterator first = x.begin() + n;
  40. iterator beg1 = first , end1 = first + n ;
  41. std::fill( norm , norm+num_of_lyap , 0.0 );
  42. // normalize first vector
  43. norm[0] = sqrt( std::inner_product( beg1 , end1 , beg1 , 0.0 ) );
  44. normalize( beg1 , end1 , norm[0] );
  45. beg1 += n;
  46. end1 += n;
  47. for( size_t j=1 ; j<num_of_lyap ; ++j , beg1+=n , end1+=n )
  48. {
  49. for( size_t k=0 ; k<j ; ++k )
  50. {
  51. tmp[k] = std::inner_product( beg1 , end1 , first + k*n , 0.0 );
  52. // clog << j << " " << k << " " << tmp[k] << "\n";
  53. }
  54. for( size_t k=0 ; k<j ; ++k )
  55. substract_vector( beg1 , end1 , first + k*n , tmp[k] );
  56. // normalize j-th vector
  57. norm[j] = sqrt( std::inner_product( beg1 , end1 , beg1 , 0.0 ) );
  58. // clog << j << " " << norm[j] << "\n";
  59. normalize( beg1 , end1 , norm[j] );
  60. }
  61. for( size_t j=0 ; j<num_of_lyap ; j++ )
  62. lyap[j] += log( norm[j] );
  63. }
  64. } // namespace odeint
  65. } // namespace numeric
  66. } // namespace boost
  67. #endif //BOOST_NUMERIC_ODEINT_GRAM_SCHMITT_HPP_INCLUDED