Stan Math Library  2.14.0
reverse mode automatic differentiation
log_sum_exp.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_REV_ARR_FUN_LOG_SUM_EXP_HPP
2 #define STAN_MATH_REV_ARR_FUN_LOG_SUM_EXP_HPP
3 
4 #include <stan/math/rev/core.hpp>
7 #include <vector>
8 #include <limits>
9 
10 namespace stan {
11  namespace math {
12 
13  namespace {
14  double log_sum_exp_as_double(const std::vector<var>& x) {
15  using std::numeric_limits;
16  using std::exp;
17  using std::log;
18  double max = -numeric_limits<double>::infinity();
19  for (size_t i = 0; i < x.size(); ++i)
20  if (x[i] > max)
21  max = x[i].val();
22  double sum = 0.0;
23  for (size_t i = 0; i < x.size(); ++i)
24  if (x[i] != -numeric_limits<double>::infinity())
25  sum += exp(x[i].val() - max);
26  return max + log(sum);
27  }
28 
29  class log_sum_exp_vector_vari : public op_vector_vari {
30  public:
31  explicit log_sum_exp_vector_vari(const std::vector<var>& x) :
32  op_vector_vari(log_sum_exp_as_double(x), x) {
33  }
34  void chain() {
35  for (size_t i = 0; i < size_; ++i) {
36  vis_[i]->adj_ += adj_ * calculate_chain(vis_[i]->val_, val_);
37  }
38  }
39  };
40  }
41 
45  inline var log_sum_exp(const std::vector<var>& x) {
46  return var(new log_sum_exp_vector_vari(x));
47  }
48 
49  }
50 }
51 #endif
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition: sum.hpp:20
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:14
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:30
fvar< T > log_sum_exp(const std::vector< fvar< T > > &v)
Definition: log_sum_exp.hpp:13
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:10
size_t size_
Definition: dot_self.hpp:18
int max(const std::vector< int > &x)
Returns the maximum coefficient in the specified column vector.
Definition: max.hpp:22
double calculate_chain(double x, double val)

     [ Stan Home Page ] © 2011–2016, Stan Development Team.