Stan Math Library  2.20.0
reverse mode automatic differentiation
ordered_constrain.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_REV_MAT_FUN_ORDERED_CONSTRAIN_HPP
2 #define STAN_MATH_REV_MAT_FUN_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_ - 1);
40 
41  y[0] = x[0];
42  for (int n = 1; n < N_; ++n) {
43  exp_x_[n - 1] = exp(x[n]);
44  y[n] = y[n - 1] + exp_x_[n - 1];
45  }
46  return y;
47  }
48 
49  /*
50  * Compute the result of multiply the transpose of the adjoint vector times
51  * the Jacobian of the ordered_constrain operator.
52  *
53  * @tparam size Number of adjoints to return
54  * @param needs_adj Boolean indicators of if adjoints of arguments will be
55  * needed
56  * @param adj Eigen::VectorXd of adjoints at the output of the softmax
57  * @return Eigen::VectorXd of adjoints propagated through softmax operation
58  */
59  template <std::size_t size>
60  auto multiply_adjoint_jacobian(const std::array<bool, size>& needs_adj,
61  const Eigen::VectorXd& adj) const {
62  Eigen::VectorXd adj_times_jac(N_);
63  double rolling_adjoint_sum = 0.0;
64 
65  if (N_ > 0) {
66  for (int n = N_ - 1; n > 0; --n) {
67  rolling_adjoint_sum += adj(n);
68  adj_times_jac(n) = exp_x_[n - 1] * rolling_adjoint_sum;
69  }
70  adj_times_jac(0) = rolling_adjoint_sum + adj(0);
71  }
72 
73  return std::make_tuple(adj_times_jac);
74  }
75 };
76 } // namespace internal
77 
86 inline Eigen::Matrix<var, Eigen::Dynamic, 1> ordered_constrain(
87  const Eigen::Matrix<var, Eigen::Dynamic, 1>& x) {
88  return adj_jac_apply<internal::ordered_constrain_op>(x);
89 }
90 
91 } // namespace math
92 } // namespace stan
93 #endif
Eigen::Matrix< T, Eigen::Dynamic, 1 > ordered_constrain(const Eigen::Matrix< T, Eigen::Dynamic, 1 > &x)
Return an increasing ordered vector derived from the specified free vector.
static STAN_THREADS_DEF AutodiffStackStorage * instance_
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:11
Eigen::VectorXd operator()(const std::array< bool, size > &needs_adj, const Eigen::VectorXd &x)
Return an increasing ordered vector derived from the specified free vector.
auto multiply_adjoint_jacobian(const std::array< bool, size > &needs_adj, const Eigen::VectorXd &adj) const
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.