Stan Math Library  2.20.0
reverse mode automatic differentiation
positive_ordered_constrain.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_REV_MAT_FUN_POSITIVE_ORDERED_CONSTRAIN_HPP
2 #define STAN_MATH_REV_MAT_FUN_POSITIVE_ORDERED_CONSTRAIN_HPP
3 
4 #include <stan/math/rev/meta.hpp>
7 #include <tuple>
8 #include <vector>
9 
10 namespace stan {
11 namespace math {
12 
13 namespace internal {
15  int N_;
16  double* exp_x_;
17 
18  public:
30  template <std::size_t size>
31  Eigen::VectorXd operator()(const std::array<bool, size>& needs_adj,
32  const Eigen::VectorXd& x) {
33  N_ = x.size();
34 
35  Eigen::Matrix<double, Eigen::Dynamic, 1> y(N_);
36  if (N_ == 0)
37  return y;
38 
39  exp_x_ = ChainableStack::instance_->memalloc_.alloc_array<double>(N_);
40 
41  exp_x_[0] = exp(x[0]);
42  y[0] = exp_x_[0];
43  for (int n = 1; n < N_; ++n) {
44  exp_x_[n] = exp(x[n]);
45  y[n] = y[n - 1] + exp_x_[n];
46  }
47  return y;
48  }
49 
50  /*
51  * Compute the result of multiply the transpose of the adjoint vector times
52  * the Jacobian of the positive_ordered_constrain operator.
53  *
54  * @tparam size Number of adjoints to return
55  * @param needs_adj Boolean indicators of if adjoints of arguments will be
56  * needed
57  * @param adj Eigen::VectorXd of adjoints at the output of the softmax
58  * @return Eigen::VectorXd of adjoints propagated through softmax operation
59  */
60  template <std::size_t size>
61  auto multiply_adjoint_jacobian(const std::array<bool, size>& needs_adj,
62  const Eigen::VectorXd& adj) const {
63  Eigen::VectorXd adj_times_jac(N_);
64  double rolling_adjoint_sum = 0.0;
65 
66  for (int n = N_; --n >= 0;) {
67  rolling_adjoint_sum += adj(n);
68  adj_times_jac(n) = exp_x_[n] * rolling_adjoint_sum;
69  }
70 
71  return std::make_tuple(adj_times_jac);
72  }
73 };
74 } // namespace internal
75 
84 inline Eigen::Matrix<var, Eigen::Dynamic, 1> positive_ordered_constrain(
85  const Eigen::Matrix<var, Eigen::Dynamic, 1>& x) {
86  return adj_jac_apply<internal::positive_ordered_constrain_op>(x);
87 }
88 
89 } // namespace math
90 } // namespace stan
91 #endif
Eigen::VectorXd operator()(const std::array< bool, size > &needs_adj, const Eigen::VectorXd &x)
Return an increasing positive ordered vector derived from the specified free vector.
static STAN_THREADS_DEF AutodiffStackStorage * instance_
auto multiply_adjoint_jacobian(const std::array< bool, size > &needs_adj, const Eigen::VectorXd &adj) const
Eigen::Matrix< T, Eigen::Dynamic, 1 > positive_ordered_constrain(const Eigen::Matrix< T, Eigen::Dynamic, 1 > &x)
Return an increasing positive ordered vector derived from the specified free vector.
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:11
T * alloc_array(size_t n)
Allocate an array on the arena of the specified size to hold values of the specified template paramet...

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