Algorith sandbox
helper_function.hpp
1 #pragma once
2 #include "algo/ad/dual.hpp"
3 #include "algo/ad/util.hpp"
4 
5 namespace algo { namespace qn { namespace detail {
6  template <typename T>
7  inline boost::numeric::ublas::vector<double>
8  calculateDerivative(
9  const std::function<ad::dual<T> (
10  const boost::numeric::ublas::vector<ad::dual<T> >& x)>& f,
11  const boost::numeric::ublas::vector<ad::dual<T>>& x)
12  {
13  return f(x).getDerivative();
14  }
15 
16  template <typename T>
17  inline boost::numeric::ublas::vector<double>
18  calculateDerivative(
19  const std::function<ad::dual<T> (
20  const boost::numeric::ublas::vector<ad::dual<T> >& x)>& f,
21  const boost::numeric::ublas::vector<double>& x)
22  {
23  namespace ublas = boost::numeric::ublas;
24  typedef ublas::vector<double> infinitesimal_type;
25  typedef ad::dual<infinitesimal_type> dual_type;
26 
27  ublas::vector<dual_type> dualX = ad::make_vector_dual(x);
28 
29  return f(dualX).getDerivative();;
30  }
31 
32  inline boost::numeric::ublas::vector<double>
33  calculateDerivative(
34  const std::function<double (
35  const boost::numeric::ublas::vector<double>& x)>& f,
36  const boost::numeric::ublas::vector<double>& x)
37  {
38  namespace ublas = boost::numeric::ublas;
39 
40  const double delta = 0.01;
41  const std::size_t size = x.size();
42  ublas::vector<double> differential(size);
43 
44  for (std::size_t i = 0; i < size; ++i) {
45  const auto unitVector = ublas::unit_vector<double>(size, i);
46  const auto& shockedVector = unitVector * delta;
47  differential(i)
48  = (f(x + shockedVector) - f(x - shockedVector)) / (2 * delta);
49  }
50 
51  return differential;
52  }
53 } } } // namespace algo { namespace qn { namespace detail {
Definition: ublas_matrix_expression_concept.hpp:5
Definition: ublas_unary_operator.hpp:13
dual class.