All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Groups
log_sum_exp.hpp
Go to the documentation of this file.
#ifndef STAN_MATH_REV_MAT_FUN_LOG_SUM_EXP_HPP
#define STAN_MATH_REV_MAT_FUN_LOG_SUM_EXP_HPP
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/scal/fun/calculate_chain.hpp>
#include <stan/math/prim/scal/fun/log_sum_exp.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <limits>
namespace stan {
namespace math {
namespace {
// these function and the following class just translate
// log_sum_exp for std::vector for Eigen::Matrix
template <int R, int C>
double log_sum_exp_as_double(const Eigen::Matrix<var, R, C>& x) {
using std::numeric_limits;
using std::exp;
using std::log;
double max = -numeric_limits<double>::infinity();
for (int i = 0; i < x.size(); ++i)
if (x(i) > max)
max = x(i).val();
double sum = 0.0;
for (int i = 0; i < x.size(); ++i)
if (x(i) != -numeric_limits<double>::infinity())
sum += exp(x(i).val() - max);
return max + log(sum);
}
class log_sum_exp_matrix_vari : public op_matrix_vari {
public:
template <int R, int C>
explicit log_sum_exp_matrix_vari(const Eigen::Matrix<var, R, C>& x) :
op_matrix_vari(log_sum_exp_as_double(x), x) {
}
void chain() {
for (size_t i = 0; i < size_; ++i) {
vis_[i]->adj_ += adj_ * calculate_chain(vis_[i]->val_, val_);
}
}
};
}
template <int R, int C>
inline var log_sum_exp(const Eigen::Matrix<var, R, C>& x) {
return var(new log_sum_exp_matrix_vari(x));
}
}
}
#endif
stan::math::sum
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition: sum.hpp:20
core.hpp
stan::math::log
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:15
stan::math::var
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:32
stan::math::log_sum_exp
fvar< T > log_sum_exp(const std::vector< fvar< T > > &v)
Definition: log_sum_exp.hpp:14
log_sum_exp.hpp
stan::math::calculate_chain
double calculate_chain(const double &x, const double &val)
Definition: calculate_chain.hpp:8
stan::math::exp
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:10
size_
size_t size_
Definition: dot_self.hpp:18
Eigen.hpp
stan::math::max
int max(const std::vector< int > &x)
Returns the maximum coefficient in the specified column vector.
Definition: max.hpp:21
calculate_chain.hpp

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